我正在创建一个应用程序,该应用程序使用以下代码通过程序关闭计算机显示:
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);
}
并获取窗口句柄,我正在使用以下代码
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
public static int getCurrentWindowHandle()
{
IntPtr hWnd = GetForegroundWindow();
int handle = hWnd.ToInt32();
return handle;
}
注意:我正在创建的这个应用程序没有 UI。
在 Visual Studio 2008 Professional 中调试时,一切正常。但是当我将exe固定到任务栏并单击它时,返回的窗口句柄为0。所以显示无法关闭。现在,从任务栏启动应用程序时,我应该怎么做才能获取窗口句柄?
示例主程序将如下所示:
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);
}