【问题标题】:Problem using WM_Close in c#在 c# 中使用 WM_Close 的问题
【发布时间】: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#


【解决方案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);

【讨论】:

  • @Peter van der Heijden,我已经按照你的建议进行了更新。但不知道如何在 closewindow() 中调用它。请帮我解决这个问题。谢谢。
  • @请注意,我的窗口不会出现在 windows 任务栏中
【解决方案2】:

你为什么要制造讨厌的黑客,而你可以打电话给Process.CloseMainWindow()?

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.closemainwindow.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-01
    • 2012-05-23
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多