Process.MainWindowHandle 的意外行为
我一直在尝试理解 Process.MainWindowHandle。
根据 MSDN; “主窗口是进程启动时创建的窗口。初始化后,可能会打开其他窗口,包括模态窗口和顶级窗口,但与进程关联的第一个窗口仍然是主窗口。” (强调)
但是在调试时我注意到 MainWindowHandle 似乎改变了值......这是我没想到的,特别是在查阅了上面的文档之后。
为了确认该行为,我创建了一个带有计时器的独立 WinForms 应用程序,每 100 毫秒检查一次“DEVENV”(Visual Studio)进程的 MainWindowHandle。
这是这个测试应用程序的有趣部分...
IntPtr oldHWnd = IntPtr.Zero;
void GetMainwindowHandle()
{
Process[] processes = Process.GetProcessesByName("DEVENV");
if (processes.Length!=1)
return;
IntPtr newHWnd = processes[0].MainWindowHandle;
if (newHWnd != oldHWnd)
{
oldHWnd = newHWnd;
textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n");
}
}
private void timer1Tick(object sender, EventArgs e)
{
GetMainwindowHandle();
}
当您(例如)单击 VS 内的下拉菜单时,您可以看到 MainWindowHandle 的值发生变化。
也许我误解了文档。
任何人都可以阐明吗?
I've been trying to understand Process.MainWindowHandle.
According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but the first window associated with the process remains the main window." (Emphasis added)
But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above.
To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms.
Here's the interesting part of this test app...
IntPtr oldHWnd = IntPtr.Zero;
void GetMainwindowHandle()
{
Process[] processes = Process.GetProcessesByName("DEVENV");
if (processes.Length!=1)
return;
IntPtr newHWnd = processes[0].MainWindowHandle;
if (newHWnd != oldHWnd)
{
oldHWnd = newHWnd;
textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n");
}
}
private void timer1Tick(object sender, EventArgs e)
{
GetMainwindowHandle();
}
You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS.
Perhaps I've misunderstood the documentation.
Can anyone shed light?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上 Process.MainWindowHandle 是最顶层窗口的句柄,它并不是真正的“主窗口句柄”
Actually Process.MainWindowHandle is a handle of top-most window, it's not really the "Main Window Handle"
@edg,
我猜这是 MSDN 中的错误。 您可以在 Relfector 中清楚地看到,.NET 中的“主窗口”检查如下所示:
当 .NET 代码枚举窗口时,很明显第一个可见窗口(即顶级窗口)将匹配此条件。
@edg,
I guess it's an error in MSDN. You can clearly see in Relfector, that "Main window" check in .NET looks like:
When .NET code enumerates windows, it's pretty obvious that first visible window (i.e. top level window) will match this criteria.