Search code examples
vb.netwakeup

How to turn on/ wake the screen with Visual Basic


I am struggling with this code for turning on the monitor. I have set in the Windows 10 control panel the display to turn off after 10 minutes, but I have one voice recognizing app written in VB and I need to wake the screen when I call the application via voice. So is there a code for waking the monitor trough Visual Basic? I searched a long time but I only find some Java code. Thanks and have a great day/night! :)


Solution

  • K, so, with the guidance of the article on codeproject, some of the answers given to this question and pinvoke.net, I've got something working. It could be cleaner, but I leave that up to you :). it is your project, after all ;).

    Imports System.Runtime.InteropServices
    
    Public Class Monitor
        Private Const WM_SYSCOMMAND As Integer = &H112
        Private Const SC_MONITORPOWER As Integer = &HF170
        Private Const HWND_BROADCAST As Integer = &HFFFF
        Private Const INPUT_MOUSE As Integer = 0
        Private Const MOUSEEVENTF_MOVE As Integer = 1
    
        <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
        Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
        End Function
    
        <DllImport("user32.dll", SetLastError:=True)>
        Private Shared Function SendInput(<[In]()> ByVal nInput As UInt32,<[In](), MarshalAs(UnmanagedType.LPArray, ArraySubtype:=UnmanagedType.Struct, SizeParamindex:=0)> ByVal pInputs() As INPUT, <[In]()> ByVal cbInput As Int32) As UInt32
        End Function
    
        Private Structure INPUT
            Public type As Integer
            Public dx As Integer
            Public dy As Integer
            Public mouseData As Integer
            Public dwFlags As Integer
            Public time As Integer
            Public dwExtraInfo As IntPtr
        End Structure
    
    
        Public Shared Sub Disable()
             SendMessage(New IntPtr(HWND_BROADCAST), WM_SYSCOMMAND, SC_MONITORPOWER, New IntPtr(2))
        End Sub
    
        Public Shared Sub Enable()
            Dim input = New INPUT()
    
            input.type = INPUT_MOUSE
            input.dx = 1
            input.dy = 0
            input.mouseData = 0
            input.dwFlags = MOUSEEVENTF_MOVE
            input.time = 0
            input.dwExtraInfo = IntPtr.Zero
    
            SendInput(1, {input}, 28)
        End Sub
    End Class