在c#中使用WM_Close

时间:2009-09-08 02:25:30

标签: c#

我使用以下代码关闭窗口,通过搜索任务栏中的窗口名称。 但在一个案例中,我的窗口不会出现在任务栏中。在这种情况下,WM_Close无法关闭窗口。是什么方法使用WM_Close ???

来做到这一点
    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)
        {
            //Free the resources of ShellBasics and terminate Daemon here.
            IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, "DAEMON TAB BAR");
            bool ret = CloseWindow(hWnd);
        }
    }

    //WM_Close
    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    static uint WM_CLOSE = 0x10;

    static bool CloseWindow(IntPtr hWnd)
    {
        SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); 
        return true;
    }

现在使用以下代码......但是

中出现错误

“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;
    }

1 个答案:

答案 0 :(得分:1)

编辑:抱歉误读了您的问题。

请改用FindWindow/FindWindowEx