[英]Using WM_Close in c#
我正在使用以下代碼以編程方式退出進程。 因為我是這個概念的新手。 我想知道如何在下面的代碼中使用此代碼。
邏輯:我將終止進程名稱,我將其分配給該函數。
如果要終止記事本,如何將參數[Process Name]傳遞給該函數?
[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);
}
使用Process.CloseMainWindow
而不是手動發送消息。 這會將消息發送到流程的主窗口:
using System.Diagnostics;
// ...
foreach (var process in Process.GetProcessesByName("notepad.exe"))
process.CloseMainWindow();
或者,您可以使用MainWindowHandle
來獲取Process
主窗口的句柄並向其發送消息:
foreach (var process in Process.GetProcessesByName("notepad.exe"))
CloseWindow(process.MainWindowHandle); // CloseWindow is defined by OP.
如果要立即終止進程而不是關閉主窗口,則這不是一個好方法。 您應該改用Process.Kill
方法。
雖然我同意Mehrdad的回答,但如果您真的想重新發明輪子,那么這就是這樣做的方法(這沒有任何錯誤檢查,請您自己添加)。
[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);
}
順便說一句, 這里是查看本機API的托管聲明的好地方
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.