Visual Basic - Codigo de Apagar el Computador

Life is soft - evento anual de software empresarial
 
Vista:

Codigo de Apagar el Computador

Publicado por Carlos Flores (8 intervenciones) el 25/09/2014 16:29:34
tengo este codigo de visual basic para apagar el computador fucniona pero no se donde me equivoque porque lo que hace es reiniciar y no quiero eso quiero que apague alguien me puede decir donde estoy fallando


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
' Shutdown Flags
Const EWX_LOGOFF = 0
Const EWX_SHUTDOWN = 1
Const EWX_REBOOT = 2
Const EWX_FORCE = 4
Const SE_PRIVILEGE_ENABLED = &H2
Const TokenPrivileges = 3
Const TOKEN_ASSIGN_PRIMARY = &H1
Const TOKEN_DUPLICATE = &H2
Const TOKEN_IMPERSONATE = &H4
Const TOKEN_QUERY = &H8
Const TOKEN_QUERY_SOURCE = &H10
Const TOKEN_ADJUST_PRIVILEGES = &H20
Const TOKEN_ADJUST_GROUPS = &H40
Const TOKEN_ADJUST_DEFAULT = &H80
Const SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
Const ANYSIZE_ARRAY = 1
Private Type LARGE_INTEGER
    lowpart As Long
    highpart As Long
End Type
Private Type Luid
    lowpart As Long
    highpart As Long
End Type
Private Type LUID_AND_ATTRIBUTES
    'pLuid As Luid
    pLuid As LARGE_INTEGER
    Attributes As Long
End Type
Private Type TOKEN_PRIVILEGES
    PrivilegeCount As Long
    Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
End Type
Private Declare Function InitiateSystemShutdown Lib "advapi32.dll" Alias "InitiateSystemShutdownA" (ByVal lpMachineName As String, ByVal lpMessage As String, ByVal dwTimeout As Long, ByVal bForceAppsClosed As Long, ByVal bRebootAfterShutdown As Long) As Long
Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, lpLuid As LARGE_INTEGER) As Long
Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function GetLastError Lib "kernel32" () As Long
Public Function InitiateShutdownMachine(ByVal Machine As String, Optional Force As Variant, Optional Restart As Variant, Optional AllowLocalShutdown As Variant, Optional Delay As Variant, Optional Message As Variant) As Boolean
    Dim hProc As Long
    Dim OldTokenStuff As TOKEN_PRIVILEGES
    Dim OldTokenStuffLen As Long
    Dim NewTokenStuff As TOKEN_PRIVILEGES
    Dim NewTokenStuffLen As Long
    Dim pSize As Long
    If IsMissing(Force) Then Force = False
    If IsMissing(Restart) Then Restart = False
    If IsMissing(AllowLocalShutdown) Then AllowLocalShutdown = True
    If IsMissing(Delay) Then Delay = 0
    If IsMissing(Message) Then Message = ""
    'Make sure the Machine-name doesn't start with '\\'
    If InStr(Machine, "\\") = 1 Then
        Machine = Right(Machine, Len(Machine) - 2)
    End If
    'check if it's the local machine that's going to be shutdown
    If (LCase(GetMyMachineName) = LCase(Machine)) Then
        'may we shut this computer down?
        If AllowLocalShutdown = False Then Exit Function
        'open access token
        If OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hProc) = 0 Then
            MsgBox "OpenProcessToken Error: " & GetLastError()
            Exit Function
        End If
        'retrieve the locally unique identifier to represent the Shutdown-privilege name
        If LookupPrivilegeValue(vbNullString, SE_SHUTDOWN_NAME, OldTokenStuff.Privileges(0).pLuid) = 0 Then
            MsgBox "LookupPrivilegeValue Error: " & GetLastError()
            Exit Function
        End If
        NewTokenStuff = OldTokenStuff
        NewTokenStuff.PrivilegeCount = 1
        NewTokenStuff.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED
        NewTokenStuffLen = Len(NewTokenStuff)
        pSize = Len(NewTokenStuff)
        'Enable shutdown-privilege
        If AdjustTokenPrivileges(hProc, False, NewTokenStuff, NewTokenStuffLen, OldTokenStuff, OldTokenStuffLen) = 0 Then
            MsgBox "AdjustTokenPrivileges Error: " & GetLastError()
            Exit Function
        End If
        'initiate the system shutdown
        If InitiateSystemShutdown("\\" & Machine, Message, Delay, Force, Restart) = 0 Then
            Exit Function
        End If
        NewTokenStuff.Privileges(0).Attributes = 0
        'Disable shutdown-privilege
        If AdjustTokenPrivileges(hProc, False, NewTokenStuff, Len(NewTokenStuff), OldTokenStuff, Len(OldTokenStuff)) = 0 Then
            Exit Function
        End If
    Else
        'initiate the system shutdown
        If InitiateSystemShutdown("\\" & Machine, Message, Delay, Force, Restart) = 0 Then
            Exit Function
        End If
    End If
    InitiateShutdownMachine = True
End Function
Function GetMyMachineName() As String
    Dim sLen As Long
    'create a buffer
    GetMyMachineName = Space(100)
    sLen = 100
    'retrieve the computer name
    If GetComputerName(GetMyMachineName, sLen) Then
        GetMyMachineName = Left(GetMyMachineName, sLen)
    End If
End Function
 
Private Sub Command1_Click()
 InitiateShutdownMachine GetMyMachineName, True, True, True, 3, "CF.Net 2015 Desactivara Finciones y Apagara el Computador..."
End Sub
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Codigo de Apagar el Computador

Publicado por Carlos Flores (8 intervenciones) el 27/09/2014 00:06:23
Nadie puede darme una respuesta de donde estoy fallando en este codigo gracias son cooperativos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Oscar

Codigo de Apagar el Computador

Publicado por Oscar (63 intervenciones) el 27/09/2014 09:18:04
LA reinicia por que en la llamada que haces tú dices que la reinicie, cuando copiaste este código de internet debiste revisarlo.

Échale un ojo al código que tienes en el botón y ya verás como rápido encuentras el problema
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Codigo de Apagar el Computador

Publicado por Carlos Flores (8 intervenciones) el 27/09/2014 14:32:04
Gracias eres muy expresivo con decirme que el error esta en los True hubiera bastado pero te lo agradezco en haberme enfocado en una zona, y los códigos de internet son para que todos los copiemos y los modifiquemos a lo que deseamos no hay necesidad de decirlo la mayoría somos copiones eso quisisteis decir gracias.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Codigo de Apagar el Computador

Publicado por Carlos Flores (8 intervenciones) el 27/09/2014 19:10:42
Les agradezco su ayuda ya solucione el error que tenia en este código, el error estaba en esta parte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  'initiate the system shutdown
        If InitiateSystemShutdown("\\" & Machine, Message, Delay, Force, Restart) = 0 Then   'aqui el fallo es shutdown en vez de restart
            Exit Function
        End If
        NewTokenStuff.Privileges(0).Attributes = 0
        'Disable shutdown-privilege
        If AdjustTokenPrivileges(hProc, False, NewTokenStuff, Len(NewTokenStuff), OldTokenStuff, Len(OldTokenStuff)) = 0 Then
            Exit Function
        End If
    Else
        'initiate the system shutdown
        If InitiateSystemShutdown("\\" & Machine, Message, Delay, Force, Restart) = 0 Then
            Exit Function
        End If

en ambos le avía colocado Restart

y era Shutdown pero le agradezco por su tiempo y si alguien le sirve este código sirve tanto para windows xp como para 7 en 8 no lo he probado quizás alguien lo haga y comente.

de esto se trata la programación si no nadie compartiera códigos en internet y los modificaran para su conveniencia
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de JoaoM
Val: 58
Ha aumentado 1 puesto en Visual Basic (en relación al último mes)
Gráfica de Visual Basic

Codigo de Apagar el Computador

Publicado por JoaoM (79 intervenciones) el 28/09/2014 01:14:06
El titulo dice:
Codigo de Apagar el Computador

Bastaria esto en un archivo hecho en block Notas y darle el nombre con extension .cmd

Hazlo y deja los archivos en el escritorio y ejecuta cualquier

1
2
3
4
5
6
7
8
9
Este reinicia
@echo off
shutdown -r -t 1
exit
 
Este apaga
@echo off
shutdown -s -t 1
exit

Para apagar o reiniciar, no entiendo el porque tanta linea de codigo, ¿podrias expliarlo? Gracias
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Codigo de Apagar el Computador

Publicado por Carlos Flores (8 intervenciones) el 29/09/2014 14:57:23
Si te lo explico es porque lo deseo colocar en un programa elaborado también en Visual Basic y quiero que en un determinado momento de la tarde el cargue otro formulario automáticamente y que diga que se apagara el sistema en ese determinado tiempo es porque en el lugar donde trabajo trabajamos por tiempo y la secretaria se retira a las 4 y los demás a las 5:40 ella apaga el sistema o nos quedamos adivinando la hora de salida ahora con este código aparecerá un mensaje que diga que no apague el sistema porque se apagara automáticamente en el tiempo requerido un simple bloc de notas si me ayuda pero seria mandar dos procesos a la ves mientras que con este código VB solo uno espero haberme expresado bien y que me entendieron cual es el propósito de tanto código gracias
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de JoaoM
Val: 58
Ha aumentado 1 puesto en Visual Basic (en relación al último mes)
Gráfica de Visual Basic

Codigo de Apagar el Computador

Publicado por JoaoM (79 intervenciones) el 30/09/2014 00:57:25
Que bien hermano, y ese codigo es en VBA? o tambien en VBA excel?

Si se puede implementar en Excel serie lo macho, l otienes completo? y como se implementaria en Excel?

Podrias facilitarnos dicho archivo ya con el codigo?
y como se ejecuta
GRacias
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar