查找 WPF 窗口的句柄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1556182/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:05:19  来源:igfitidea点击:

Finding the handle to a WPF window

wpfwindowhandle

提问by Evan

Windows forms had a property win1.Handle which, if I recall, returns the handle of the main window handle?

Windows 窗体有一个属性 win1.Handle,如果我记得,它返回主窗口句柄的句柄?

Is there an equivalent way to get the handle of a WPF Window?

有没有等效的方法来获取 WPF 窗口的句柄?

I found the following code online,

我在网上找到了以下代码,

IntPtr windowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;

but I don't think that will help me because my application has multiple windows.

但我认为这对我没有帮助,因为我的应用程序有多个窗口。

Thanks!!

谢谢!!

回答by Gregory Higley

Well, instead of passing Application.Current.MainWindow, just pass a reference to whichever window it is you want: new WindowInteropHelper(this).Handleand so on.

好吧,而不是传递Application.Current.MainWindow,只需传递对您想要的任何窗口的引用:new WindowInteropHelper(this).Handle等等。

回答by Reed Copsey

Just use your window with the WindowsInteropHelper class:

只需将您的窗口与 WindowsInteropHelper 类一起使用:

// ... Window myWindow = get your Window instance...
IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;

Right now, you're asking for the Application's main window, of which there will always be one. You can use this same technique on any Window, however, provided it is a System.Windows.Window derived Window class.

现在,您正在请求应用程序的主窗口,其中总会有一个。您可以在任何 Window 上使用相同的技术,但是,只要它是 System.Windows.Window 派生的 Window 类。

回答by Amer Sawan

you can use :

您可以使用 :

Process.GetCurrentProcess().MainWindowHandle

回答by dustyburwell

If you want window handles for ALL of your application's Windows for some reason, you can use the Application.Windowsproperty to get at all the Windows and then use WindowInteropHandlerto get at their handles as you have already demonstrated.

如果Window出于某种原因需要所有应用程序的窗口句柄,您可以使用该Application.Windows属性获取所有 Windows,然后使用WindowInteropHandler获取它们的句柄,正如您已经演示的那样。