このページをはてなブックマークに追加このページを含むはてなブックマーク このページをlivedoor クリップに追加このページを含むlivedoor クリップ

スリープモード抑止

  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
Public Class Form1
    Private previousExecutionState As Long = 0D
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load
        previousExecutionState = DisableSleepMode()
        If previousExecutionState = 0 Then
            MessageBox.Show("スリープ解除失敗。")
        End If
    End Sub
 
    Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) _
    Handles MyBase.FormClosing
        SetSleepMode(previousExecutionState)
    End Sub
 
    ''' <summary>
    ''' スリープモードを抑止にする.
    ''' </summary>
    ''' <returns>無効にする前のスリープモード状態</returns>
    ''' <remarks></remarks>
    Private Function DisableSleepMode() As Long
        Return SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED Or EXECUTION_STATE.ES_CONTINUOUS)
    End Function
 
    ''' <summary>
    ''' 指定したスリープモード状態にする.
    ''' </summary>
    ''' <param name="state">スリープモード状態</param>
    ''' <remarks></remarks>
    Private Sub SetSleepMode(ByVal state As Long)
        SetThreadExecutionState(state)
    End Sub
 
    ''' <summary>
    ''' スリープモードの抑止を解除する.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub EnableSleepMode()
        SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS)
    End Sub
 
    Private Enum EXECUTION_STATE As Integer
        ES_SYSTEM_REQUIRED = &H1
        ES_DISPLAY_REQUIRED = &H2
        ES_USER_PRESENT = &H4
        ES_CONTINUOUS = &H80000000
    End Enum
 
    Private Declare Auto Function SetThreadExecutionState Lib "kernel32.dll" ( _
        ByVal esFlags As Long _
    ) As Long
End Class