C# 如何按名称关闭窗口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9248444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to close the window by its name?
提问by Artem Tsarionov
I want to close window with some name (any application, for example, calculator and etc.). How to do it in C#? Import WinAPI functions?
我想关闭带有某个名称的窗口(任何应用程序,例如计算器等)。如何在 C# 中做到这一点?导入 WinAPI 函数?
采纳答案by Sergey Brunov
Yes, you should import the Windows API functions: FindWindow(), SendMessage(); and WM_CLOSEconstant.
是的,您应该导入 Windows API 函数:FindWindow(), SendMessage(); 和WM_CLOSE常数。
Native definitions of the Windows API functions:
Windows API 函数的本机定义:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/// <summary>
/// Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.
/// </summary>
[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);
const UInt32 WM_CLOSE = 0x0010;
Client code:
客户端代码:
IntPtr windowPtr = FindWindowByCaption(IntPtr.Zero, "Untitled - Notepad");
if (windowPtr == IntPtr.Zero)
{
Console.WriteLine("Window not found");
return;
}
SendMessage(windowPtr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
回答by Steven Palmer
You're trying to close windows belonging to other processes. That isn't something you can assume will go reliably. For one thing, YOU don't own those windows so YOU don't really have any automatic entitlement to go and mess with the other processes' windows.
您正在尝试关闭属于其他进程的窗口。这不是您可以假设会可靠进行的事情。一方面,您不拥有这些窗口,因此您实际上没有任何自动权利去处理其他进程的窗口。
As the other answer suggests, you can try sending a WM_CLOSE to the window but it comes with the caveat that the other process isn't really entitled to honour it. The response to WM_CLOSE can be anything to acceptance and a clean shutdown to outright rejection. In the latter case, you've really got no option. It's not your process. In between, as you've seen, there could be any sort of intermediate windows, dialog boxes, etc, that you'd have to contend with.
正如另一个答案所暗示的那样,您可以尝试向窗口发送 WM_CLOSE ,但需要注意的是,另一个进程并没有真正有权尊重它。对 WM_CLOSE 的响应可以是任何接受和彻底关闭的彻底拒绝。在后一种情况下,你真的别无选择。这不是你的过程。如您所见,在两者之间,可能存在您必须应对的任何类型的中间窗口、对话框等。
So what are you trying to achieve here? Why are you trying to close windows belonging to other processes? It might help to clarify what the aim is.
那么你想在这里实现什么?为什么要关闭属于其他进程的窗口?这可能有助于澄清目标是什么。

