【发布时间】:2012-01-02 14:46:54
【问题描述】:
我正在尝试使用下面的代码来关闭窗口。
但出现错误
"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;
}
【问题讨论】:
-
参数与方法不匹配。
-
您在 CloseWindow 中的初始代码似乎没问题。您可能需要检查 FindWindow 的返回值是否为 IntPtr.Zero。如果是这样,则找不到您尝试关闭的窗口。否则只需使用 hWnd 作为参数调用您原来的 CloseWindow。
标签: c#