0
votes

I am trying to use the below code to close the window.

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 ??? And there is also some problem in the parameters i pass.


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

After modification of code, but still no luck. since i am new to windows messaging kinda stuff.

    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;
    }
2
The parameters does not match the method.Anuya
Your initial code in CloseWindow seems OK. You might want to check if the return value of FindWindow is IntPtr.Zero. If so, the window you are trying to close is not found. Else just call your original CloseWindow with hWnd as parameter.Peter van der Heijden

2 Answers

1
votes

If I understand correctly what you are trying to do you should first get the window handle of the window you want to close using FindWindow. Your code would look something like this:

IntPtr hWnd = FindWindow(null, <WindowName>);
bool ret = CloseWindow(hWnd);

Define FindWindow as:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
0
votes