Evitar bloqueo windows 7

Iniciado por Amaro, 19 Enero 2016, 09:51 AM

0 Miembros y 1 Visitante están viendo este tema.

Amaro

Buenas, pues os comento, tengo el siguiente problema y es que tengo una aplicación muy simple para que mueva, con un timer, la posición del ratón. Esta funciona perfectamente en windows xp (ya esta probada) pero en windows 7 no entiendo porqué no funciona. Así que la pregunta es si alguien ha hecho al similar que evite el bloqueo/suspensión del pc.

Un saludo y gracias de antemano.

Eleкtro

Para evitar la suspensión/bloqueo del equipo puedes utilizar la función SetThreadExecutionState de la WinAPI con la que debes enviar una señal cada cierto tiempo para mentenerlo "despierto".


No puedo ayudarte mucho mostrándote código en Vb6, pero de todas formas creo que estos ejemplos en VB.Net te ayudarán, con lo que encuentres por ti mismo en Google sobre el uso de dicha función en VB6...

P/Invokes:
Código (vbnet) [Seleccionar]
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Enables an application to inform the system that it is in use,
       ''' thereby preventing the system from entering sleep or turning off the display while the application is running.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <remarks>
       ''' <see href="http://msdn.microsoft.com/es-es/library/windows/desktop/aa373208%28v=vs.85%29.aspx"/>
       ''' </remarks>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="esFlags">
       ''' The thread's execution requirements.
       ''' <para></para>
       ''' This parameter can be one or more of the <see cref="ExecutionState"/> values.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' If the function succeeds, the return value is the previous thread's <see cref="ExecutionState"/> value.
       ''' <para></para>
       ''' If the function fails, the return value is <see langword="Nothing"/>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DllImport("kernel32.dll", SetLastError:=True)>
       Public Shared Function SetThreadExecutionState(ByVal esFlags As ExecutionState
       ) As ExecutionState
       End Function


Enumeraciones:
Código (vbnet) [Seleccionar]
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Enables an application to inform the system that it is in use,
   ''' thereby preventing the system from entering sleep or turning off the display while the application is running.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' <see href="http://msdn.microsoft.com/es-es/library/windows/desktop/aa373208%28v=vs.85%29.aspx"/>
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   <Flags>
   Public Enum ExecutionState As UInteger

       ''' <summary>
       ''' Any state.
       ''' <para></para>
       ''' Don't use this value.
       ''' This value is used to detect a <see cref="ExecutionState"/> function fail.
       ''' </summary>
       None = &H0UI

       ''' <summary>
       ''' Enables away mode.
       ''' This value must be specified with <see cref="ExecutionState.Continuous"/>.
       ''' <para></para>
       ''' Away mode should be used only by media-recording and media-distribution applications that must
       ''' perform critical background processing on desktop computers while the computer appears to be sleeping.
       ''' <para></para>
       ''' Windows Server 2003: <see cref="ExecutionState.AwaymodeRequired"/> is not supported.
       ''' </summary>
       AwaymodeRequired = &H40UI

       ''' <summary>
       ''' Informs the system that the state being set should remain in effect until the
       ''' next call that uses <see cref="ExecutionState.Continuous"/> and one of the other <see cref="ExecutionState"/> flags is cleared.
       ''' </summary>
       Continuous = &H80000000UI

       ''' <summary>
       ''' Forces the display to be on by resetting the display idle timer.
       ''' <para></para>
       ''' Windows 8: This flag can only keep a display turned on, it can't turn on a display that's currently off.
       ''' </summary>
       DisplayRequired = &H2UI

       ''' <summary>
       ''' Forces the system to be in the working state by resetting the system idle timer.
       ''' </summary>
       SystemRequired = &H1UI

       ''' <summary>
       ''' This value is not supported.
       ''' <para></para>
       ''' If <see cref="ExecutionState.UserPresent"/> is combined with other <see cref="ExecutionState"/> values,
       ''' the call will fail and none of the specified states will be set.
       ''' </summary>
       UserPresent = &H4UI

   End Enum


A la función deberías pasarle los siguientes flags como te muestro en este ejemplo que escribí para Visual Basic.Net:
Código (vbnet) [Seleccionar]
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Sends an Awake signal to prevent the system from turning off the display and entering into Sleep or Hibernation modes.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>
''' The Awake signal should be sent periodically.
''' </remarks>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' <see langword="True"/> if operation succeeds, <see langword="False"/>  otherwise.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <exception cref="Win32Exception">
''' </exception>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Shared Function SendAwakeSignal() As Boolean

   Dim result As ExecutionState = ExecutionState.None
   Dim win32Err As Integer

   result = NativeMethods.SetThreadExecutionState(ExecutionState.Continuous Or
                                                  ExecutionState.SystemRequired Or
                                                  ExecutionState.DisplayRequired Or
                                                  ExecutionState.AwaymodeRequired)

   win32Err = Marshal.GetLastWin32Error

   If (result = ExecutionState.None) Then
       Throw New Win32Exception([error]:=win32Err)

   Else
       Return True

   End If

End Function


Ten en cuenta que volver a permitir la suspensión es responsabilidad tuya, y lo harías llamando a la misma función Win32.
Ejemplo, en Vb.Net:
Código (vbnet) [Seleccionar]
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Removes any previouslly sent Awake signal.
''' <para></para>
''' Call this function to return to previous state when the caller thread has finished.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' <see langword="True"/> if operation succeeds, <see langword="False"/>  otherwise.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <exception cref="Win32Exception">
''' </exception>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Shared Function RemoveAwakeSignal() As Boolean

   Dim result As ExecutionState = ExecutionState.None
   Dim win32Err As Integer

   result = NativeMethods.SetThreadExecutionState(ExecutionState.Continuous)
   win32Err = Marshal.GetLastWin32Error

   If (result = ExecutionState.None) Then
       Throw New Win32Exception([error]:=win32Err)

   Else
       Return True

   End If

End Function


Un ejemplo de uso de ambas funciones, en Vb.Net:
Código (vbnet) [Seleccionar]
Public Class Form1 : Inherits Form

    Private WithEvents awakeTimer As Threading.Timer
    Private ReadOnly awakeInterval As Integer = 30000 'ms

    Public Sub New()

        Me.InitializeComponent()
        Me.awakeTimer = New Threading.Timer(AddressOf Me.AwakeTimer_Callback, Nothing, Me.awakeInterval, 0)

    End Sub

    Private Sub AwakeTimer_Callback(ByVal stateInfo As Object)

        ' Send periodically an Awake signal to avoid the system entering into Sleep or Hibernation mode.
        Power.SendAwakeSignal()

        If (Me.awakeTimer IsNot Nothing) Then
            Me.awakeTimer.Change(Me.awakeInterval, 0)
        End If

    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) _
    Handles MyBase.FormClosing

        Me.awakeTimer.Dispose()
        Me.awakeTimer = Nothing
        Power.RemovedAwakeSignal()

    End Sub

End Class


Los códigos los saqué de mi API ElektroKit:



Saludos