我正在尝试使用以下代码关闭窗口。
但在
中收到错误“IntPtr hWnd = PostMessage(IntPtr.Zero,WM_CLOSE,IntPtr.Zero,IntPtr.Zero);”
在哪里提供窗口名称以便关闭??? 而且我传递的参数也存在一些问题。
void DaemonTerminamtionHook_KeyPressed(object sender, KeyPressedEventArgs e)
{
DaemonResult = MessageBox.Show("Are you sure, you want to Terminate Daemon?", "Terminate Daemon", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
if (DaemonResult == DialogResult.Yes)
{
IntPtr hWnd = PostMessage(IntPtr.Zero, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
bool ret = CloseWindow(hWnd);
}
}
static uint WM_CLOSE = 0x10;
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
static bool CloseWindow(IntPtr hWnd)
{
bool returnValue = PostMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
if (!returnValue)
throw new Win32Exception(Marshal.GetLastWin32Error());
return true;
}
修改代码后,仍然没有运气。因为我是Windows新闻的新手。
void DaemonTerminamtionHook_KeyPressed(object sender, KeyPressedEventArgs e)
{
DaemonResult = MessageBox.Show("Are you sure, you want to Terminate Daemon?", "Terminate Daemon", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
if (DaemonResult == DialogResult.Yes)
{
IntPtr hWnd = FindWindow(null, "DAEMON TAB BAR");
bool ret = CloseWindow(hWnd);
}
}
static bool CloseWindow(IntPtr hWnd)
{
//How to call it here
return true;
}
答案 0 :(得分:1)
如果我正确理解您要执行的操作,则应首先使用FindWindow
获取要关闭的窗口的窗口句柄。您的代码看起来像这样:
IntPtr hWnd = FindWindow(null, <WindowName>);
bool ret = CloseWindow(hWnd);
将FindWindow
定义为:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
答案 1 :(得分:0)
你为什么要制作讨厌的黑客,而你可以打电话给Process.CloseMainWindow()
?
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.closemainwindow.aspx