简体   繁体   中英

Using WM_Close in c#

I am using the below code to close the window, by searching the window name in taskbar. But i one case, my window will not appear in the taskbar. In that case, WM_Close could not close the window. Whats the other way to do it using 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;
    }

Now using the below code...But getting error in

"IntPtr hWnd = PostMessage(IntPtr.Zero, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);"

where to provide the window name in order to close that ???


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

Edit: Sorry misread your question.

Use FindWindow/FindWindowEx instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM