I am creating an application that turns off the computer display via program using the following code:
private const int WM_SYSCOMMAND = 0x0112;
private const int SC_MONITORPOWER = 0xF170;
[DllImport("user32.dll")]
private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
public void turnOffMonitor(int Handle)
{
SendMessage(Handle, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
}
and to get the window handle i'm using the following code
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
public static int getCurrentWindowHandle()
{
IntPtr hWnd = GetForegroundWindow();
int handle = hWnd.ToInt32();
return handle;
}
Note: This application i am creating has no UI.
Every thing works fine when debugging it in Visual studio 2008 professional. But when i pin the exe to the task bar and click it the window handle returned is 0. So the display fails to turn off. Now, what should i do to get the window handle when launching the application from the task bar?
The Example Main Program will be like this:
static class Program
{
private static const int WM_SYSCOMMAND = 0x0112;
private static const int SC_MONITORPOWER = 0xF170;
[DllImport("user32.dll")]
private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
IntPtr hWnd = GetForegroundWindow();
int handle = hWnd.ToInt32()
SendMessage(handle, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
}