elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Apagar el PC con un botón
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Apagar el PC con un botón  (Leído 5,248 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Apagar el PC con un botón
« en: 29 Diciembre 2009, 01:37 am »

Hola:

Tengo un Form y un button1 con Visual C# Express 2010 Beta 2. ¿Existe la manera de que al pulsar el botón se apague el equipo completo?



A veces puede ocurrir de que te salga una ventana que te dice Finalizar tarea y el equipo no se apaga. Si es posible hacerlo lo de apagar el equipo con un botón. ¿Hay una forma de evitar la posible ventana de Finalizar tarea?

Salu2.


« Última modificación: 29 Diciembre 2009, 01:38 am por Meta » En línea

seba123neo


Desconectado Desconectado

Mensajes: 3.621



Ver Perfil WWW
Re: Apagar el PC con un botón
« Respuesta #1 en: 29 Diciembre 2009, 02:47 am »

Hola, en visual basic 6 hay una forma de forzar el apagado con la api AdjustTokenPrivileges, fijate si hay algo parecido en C#, debe haber seguro...

saludos.


En línea

raul338


Desconectado Desconectado

Mensajes: 2.633


La sonrisa es la mejor forma de afrontar las cosas


Ver Perfil WWW
Re: Apagar el PC con un botón
« Respuesta #2 en: 29 Diciembre 2009, 13:58 pm »

Hola, en visual basic 6 hay una forma de forzar el apagado con la api AdjustTokenPrivileges, fijate si hay algo parecido en C#, debe haber seguro...

saludos.

Exacto, tienes que usar la API, y apagar "a la fuerza", te paso parte de una aplicacion que hize recopilando codigos de internet (la aplicacion era para apagar la PC a determinada hora, con el shutdown.exe era dificil calcular en cuantos segundos queria q se apage :P)

Código
  1. #region "- Delcaraciones API -"
  2. <DllImport("user32.dll", SetLastError:=True)> _
  3.    Function ExitWindowsEx( _
  4.     ByVal uFlags As ExitWindows, _
  5.     ByVal dwReason As ShutdownReason) As <MarshalAs(UnmanagedType.Bool)> Boolean
  6.    End Function
  7.  
  8.    <Flags()> _
  9.    Enum ExitWindows As UInteger
  10.        LogOff = &H0
  11.        ShutDown = &H1
  12.        Reboot = &H2
  13.        PowerOff = &H8
  14.        RestartApps = &H40
  15.        ' plus AT MOST ONE of the following two:
  16.        Force = &H4
  17.        ForceIfHung = &H10
  18.    End Enum
  19.  
  20.    <Flags()> _
  21. Enum ShutdownReason As UInteger
  22.        MajorApplication = &H40000
  23.        MajorHardware = &H10000
  24.        MajorLegacyApi = &H70000
  25.        MajorOperatingSystem = &H20000
  26.        MajorOther = &H0
  27.        MajorPower = &H60000
  28.        MajorSoftware = &H30000
  29.        MajorSystem = &H50000
  30.  
  31.        MinorBlueScreen = &HF
  32.        MinorCordUnplugged = &HB
  33.        MinorDisk = &H7
  34.        MinorEnvironment = &HC
  35.        MinorHardwareDriver = &HD
  36.        MinorHotfix = &H11
  37.        MinorHung = &H5
  38.        MinorInstallation = &H2
  39.        MinorMaintenance = &H1
  40.        MinorMMC = &H19
  41.        MinorNetworkConnectivity = &H14
  42.        MinorNetworkCard = &H9
  43.        MinorOther = &H0
  44.        MinorOtherDriver = &HE
  45.        MinorPowerSupply = &HA
  46.        MinorProcessor = &H8
  47.        MinorReconfig = &H4
  48.        MinorSecurity = &H13
  49.        MinorSecurityFix = &H12
  50.        MinorSecurityFixUninstall = &H18
  51.        MinorServicePack = &H10
  52.        MinorServicePackUninstall = &H16
  53.        MinorTermSrv = &H20
  54.        MinorUnstable = &H6
  55.        MinorUpgrade = &H3
  56.        MinorWMI = &H15
  57.  
  58.        FlagUserDefined = &H40000000
  59.        FlagPlanned = &H80000000&
  60.    End Enum
  61.  
  62.    'This routine enables the Shutdown privilege for the current process,
  63.    'which is necessary if you want to call ExitWindowsEx.
  64.  
  65.    Const ANYSIZE_ARRAY As Integer = 1
  66.    Const TOKEN_QUERY As Integer = &H8
  67.    Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20
  68.    Const SE_SHUTDOWN_NAME As String = "SeShutdownPrivilege"
  69.    Const SE_PRIVILEGE_ENABLED As Integer = &H2
  70.  
  71.    <StructLayout(LayoutKind.Sequential)> _
  72.    Private Structure LUID
  73.        Public LowPart As UInt32
  74.        Public HighPart As UInt32
  75.    End Structure
  76.  
  77.    <StructLayout(LayoutKind.Sequential)> _
  78.    Private Structure LUID_AND_ATTRIBUTES
  79.        Public Luid As LUID
  80.        Public Attributes As UInt32
  81.    End Structure
  82.  
  83.    <StructLayout(LayoutKind.Sequential)> _
  84.    Private Structure TOKEN_PRIVILEGES
  85.        Public PrivilegeCount As UInt32
  86.        <MarshalAs(UnmanagedType.ByValArray, SizeConst:=ANYSIZE_ARRAY)> _
  87.        Public Privileges() As LUID_AND_ATTRIBUTES
  88.    End Structure
  89.  
  90.    <DllImport("advapi32.dll", SetLastError:=True)> _
  91.    Private Function LookupPrivilegeValue( _
  92.     ByVal lpSystemName As String, _
  93.     ByVal lpName As String, _
  94.     ByRef lpLuid As LUID _
  95.      ) As Boolean
  96.    End Function
  97.  
  98.    <DllImport("advapi32.dll", SetLastError:=True)> _
  99.    Private Function OpenProcessToken( _
  100.     ByVal ProcessHandle As IntPtr, _
  101.     ByVal DesiredAccess As Integer, _
  102.     ByRef TokenHandle As IntPtr _
  103.      ) As Boolean
  104.    End Function
  105.  
  106.    <DllImport("kernel32.dll", SetLastError:=True)> _
  107.    Private Function CloseHandle(ByVal hHandle As IntPtr) As Boolean
  108.    End Function
  109.  
  110.    <DllImport("advapi32.dll", SetLastError:=True)> _
  111.    Private Function AdjustTokenPrivileges( _
  112.       ByVal TokenHandle As IntPtr, _
  113.       ByVal DisableAllPrivileges As Boolean, _
  114.       ByRef NewState As TOKEN_PRIVILEGES, _
  115.       ByVal BufferLength As Integer, _
  116.       ByRef PreviousState As TOKEN_PRIVILEGES, _
  117.       ByRef ReturnLength As IntPtr _
  118.     ) As Boolean
  119.    End Function
  120.  
  121.    Public Sub AcquireShutdownPrivilege()
  122.  
  123.        Dim lastWin32Error As Integer = 0
  124.  
  125.        'Get the LUID that corresponds to the Shutdown privilege, if it exists.
  126.        Dim luid_Shutdown As LUID
  127.        If Not LookupPrivilegeValue(Nothing, SE_SHUTDOWN_NAME, luid_Shutdown) Then
  128.            lastWin32Error = Marshal.GetLastWin32Error()
  129.            Throw New System.ComponentModel.Win32Exception(lastWin32Error, _
  130.             "LookupPrivilegeValue failed with error " & lastWin32Error.ToString & ".")
  131.        End If
  132.  
  133.        'Get the current process's token.
  134.        Dim hProc As IntPtr = Process.GetCurrentProcess().Handle
  135.        Dim hToken As IntPtr
  136.        If Not OpenProcessToken(hProc, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hToken) Then
  137.            lastWin32Error = Marshal.GetLastWin32Error()
  138.            Throw New System.ComponentModel.Win32Exception(lastWin32Error, _
  139.             "OpenProcessToken failed with error " & lastWin32Error.ToString & ".")
  140.        End If
  141.  
  142.        Try
  143.  
  144.            'Set up a LUID_AND_ATTRIBUTES structure containing the Shutdown privilege, marked as enabled.
  145.            Dim luaAttr As New LUID_AND_ATTRIBUTES
  146.            luaAttr.Luid = luid_Shutdown
  147.            luaAttr.Attributes = SE_PRIVILEGE_ENABLED
  148.  
  149.            'Set up a TOKEN_PRIVILEGES structure containing only the shutdown privilege.
  150.            Dim newState As New TOKEN_PRIVILEGES
  151.            newState.PrivilegeCount = 1
  152.            newState.Privileges = New LUID_AND_ATTRIBUTES() {luaAttr}
  153.  
  154.            'Set up a TOKEN_PRIVILEGES structure for the returned (modified) privileges.
  155.            Dim prevState As TOKEN_PRIVILEGES = New TOKEN_PRIVILEGES
  156.            ReDim prevState.Privileges(CInt(newState.PrivilegeCount))
  157.  
  158.            'Apply the TOKEN_PRIVILEGES structure to the current process's token.
  159.            Dim returnLength As IntPtr
  160.            If Not AdjustTokenPrivileges(hToken, False, newState, Marshal.SizeOf(prevState), prevState, returnLength) Then
  161.                lastWin32Error = Marshal.GetLastWin32Error()
  162.                Throw New System.ComponentModel.Win32Exception(lastWin32Error, _
  163.                 "AdjustTokenPrivileges failed with error " & lastWin32Error.ToString & ".")
  164.            End If
  165.  
  166.        Finally
  167.            CloseHandle(hToken)
  168.        End Try
  169.  
  170.    End Sub
  171. #End Region
  172.  
  173. Sub ApagarWindows()
  174.            Call AcquireShutdownPrivilege()
  175.            Call ExitWindowsEx(ExitWindows.ShutDown, ShutdownReason.MajorApplication)
  176. End Sub
  177.  

Ahora encargate de pasar eso a C#  ;D

PInvoke te puede ayudar para las API, guarda el link  ;)
En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Apagar el PC con un botón
« Respuesta #3 en: 30 Diciembre 2009, 02:28 am »

Muchas gracias, es mucho código para lo que es. Da la casualdiad que hay estos:

http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html

http://www.elguille.info/colabora/2007/phanthom2k_ApagadoPC.htm

Saludo.
En línea

nico56

Desconectado Desconectado

Mensajes: 246


Ver Perfil
Re: Apagar el PC con un botón
« Respuesta #4 en: 30 Diciembre 2009, 18:05 pm »

E c/c++ tenia la funcion system("comando"), donde comando era cualquier comando del sistema operativo, ahi podrias poner un shutdown con las opciones de forzado apagado. Para mas info de ese comando en un cmd pone "shutdown /?"
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Dos veces al botón Apagar para que se apague pc
Software
Ganejash 5 2,508 Último mensaje 15 Marzo 2013, 18:17 pm
por 1mpuls0
¿Es malo apagar el ordenador del botón?
Noticias
wolfbcn 7 2,613 Último mensaje 14 Diciembre 2017, 18:52 pm
por Lurker
Apagar monitor sin bloquear el sistema! « 1 2 »
Windows
TrashAmbishion 15 6,571 Último mensaje 8 Diciembre 2021, 15:20 pm
por Randomize
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines