wpf 如何获取进程的主窗口(不是窗口句柄)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18442454/
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 Get the Main Window of a process(not the window handle)?
提问by Anee
I have been trying to get the Reference to the Main window of my Process for quite sometime. I went through many sites looking for a solution. But it looks like everyone provides a solution to get the Window handle and not the window itself.
一段时间以来,我一直在尝试获取对我的进程的主窗口的引用。我浏览了许多网站以寻找解决方案。但看起来每个人都提供了获取 Window 句柄而不是窗口本身的解决方案。
Getting a Process's Mainwindow handle is quite straight forward. I seem to get the Window title also as expected.
获取进程的 Mainwindow 句柄非常简单。我似乎也按预期获得了 Window 标题。
I went through most of the APIs provided by User32.dll but couldn't find what i was looking for.
我浏览了 User32.dll 提供的大部分 API,但找不到我要找的东西。
I need a reference to the window because i want to access few members of the window class to accomplish my work. The window i am referring to is a WPF window.
我需要对窗口的引用,因为我想访问窗口类的几个成员来完成我的工作。我所指的窗口是 WPF 窗口。
Any help in this regard will be highly appreciated:)
在这方面的任何帮助将不胜感激:)
Thanks in advance.
提前致谢。
回答by sloth
You can use the HwndSource.FromHwndmethod.
您可以使用该HwndSource.FromHwnd方法。
Here's a simple LinqPad-ready example:
这是一个简单的 LinqPad 就绪示例:
void Main()
{
var mw = new MainW();
mw.Show();
var hWnd = FindWindowByCaption(IntPtr.Zero, "testwindow");
var rootVisual = System.Windows.Interop.HwndSource.FromHwnd(hWnd).RootVisual;
MainW m2 = (MainW)rootVisual;
Thread.Sleep(500);
m2.Title="is going";
Thread.Sleep(500);
m2.Title="to close...";
Thread.Sleep(500);
m2.Close();
}
[System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
class MainW: System.Windows.Window
{
public MainW()
{
Title = "testwindow";
Width = 230;
Height = 100;
Background = System.Windows.Media.Brushes.AliceBlue;
}
}

