简体   繁体   中英

Using WM_Close in c#

I am using the below code to exit a process programatically. since i am new to this concept. I want to know how to use this below code.

Logic : I will have the process name to be terminated, i shud assign that to this function.

Say if want to terminate a notepad, how to pass parameter [Process Name] to this function ?

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
    static uint WM_CLOSE = 0xF060;

    public void CloseWindow(IntPtr hWindow)
    {
        SendMessage(hWindow, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
    }

Use the Process.CloseMainWindow instead of manually sending the message. This will send the message to the main window of the process:

using System.Diagnostics;
// ...

foreach (var process in Process.GetProcessesByName("notepad.exe"))
    process.CloseMainWindow();

Alternatively, you can use MainWindowHandle to get the handle of the main window of a Process and send a message to it:

foreach (var process in Process.GetProcessesByName("notepad.exe"))
    CloseWindow(process.MainWindowHandle); // CloseWindow is defined by OP.

If you want to kill the process immediately instead of closing the main window, this is not a good approach. You should use the Process.Kill method instead.

Although I agree with Mehrdad's answer but if you really want to re-invent the wheel, then this is how to do it (This is without any error checking etc. Please add that yourself).

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


static void Main()
{
    IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, "Untitled - Notepad");
    bool ret = CloseWindow(hWnd);
}

BTW, Here is a good place to view Managed declarations of native API's

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