我正在使用以下代码创建一个通过程序关闭计算机显示的应用程序:
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;
}
注意:我正在创建的此应用程序没有用户界面。
在Visual Studio 2008专业版中调试它时,每件事都可以正常工作。 但是当我将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);
}