How do I turn off a monitor using VB.NET code? OK, actually I found the C# solution. But I need the VB.NET solution. I have tried an online C# to VB.NET converter, but the converter is complaining that there are errors in it.
How can the following C# code be translated to VB.NET?
using System.Runtime.InteropServices; //to DllImport
public int WM_SYSCOMMAND = 0x0112;
public int SC_MONITORPOWER = 0xF170; //Using the system pre-defined MSDN constants that can be used by the SendMessage() function .
[DllImport("user32.dll")]
private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
//To call a DLL function from C#, you must provide this declaration.
private void button1_Click(object sender, System.EventArgs e)
{
SendMessage( this.Handle.ToInt32() , WM_SYSCOMMAND , SC_MONITORPOWER ,2 );//DLL function
}
UPDATE:
I use the online developer Fusion converter.
Try this
Public WM_SYSCOMMAND As Integer = &H112
Public SC_MONITORPOWER As Integer = &Hf170
<DllImport("user32.dll")> _
Private Shared Function SendMessage(hWnd As Integer, hMsg As Integer, wParam As Integer, lParam As Integer) As Integer
End Function
Private Sub button1_Click(sender As Object, e As System.EventArgs)
SendMessage(Me.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 2)
End Sub
Yes, the declarations in the accepted answer are not correct. Random failure is possible on a 64-bit version of Windows since the passed arguments have the wrong size. They should look like this:
Private Const WM_SYSCOMMAND As Integer = &H112
Private Const SC_MONITORPOWER As Integer = &HF170
Private Const MonitorToLowPower As Integer = 1
Private Const MonitorShutoff As Integer = 2
<DllImport("user32.dll")> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal hMsg As Integer, _
ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SendMessage(Me.Handle, WM_SYSCOMMAND,
CType(SC_MONITORPOWER, IntPtr), CType(MonitorShutoff, IntPtr))
End Sub
You could add a check on the return value of SendMessage(), it should return IntPtr.Zero. Not so sure it is useful, it will be pretty obvious to the user that the command didn't work for some reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With