Windows 窗体有一个属性 win1.Handle,如果我没记错的话,它返回主窗口句柄的句柄?
是否存在获取 WPF 窗口句柄的等效方法?
我在网上找到了以下代码,
IntPtr windowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
但我不认为这对我有帮助,因为我的应用程序有多个窗口。
只要在窗口中使用 WindowsInteropHelper 类:
// ... Window myWindow = get your Window instance... IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;
现在,您要求应用程序的主窗口,其中总是有一个。但是,您可以在任何窗口上使用相同的技术,只要它是系统。窗户。窗口派生的窗口类。
如果出于某种原因希望所有应用程序的 Window都有窗口句柄,可以使用 Application.Windows属性获取所有 Windows,然后使用 WindowInteropHandler获取它们的句柄,如前所述。
Window
Application.Windows
WindowInteropHandler
那么,不要传递 Application.Current.MainWindow,只要传递一个引用到您想要的任何窗口: new WindowInteropHelper(this).Handle等等。
Application.Current.MainWindow
new WindowInteropHelper(this).Handle
你可使用:
Process.GetCurrentProcess().MainWindowHandle
在我的用例中,在启动时我需要一个主窗口的句柄,而且无论我做什么,我都不能让 new WindowInteropHelper(...).Handle返回一个空句柄以外的任何东西,因为窗口还没有被初始化。
new WindowInteropHelper(...).Handle
可以使用 EnsureHandle()方法,如果句柄不存在,它将创建句柄,如果存在,则返回当前句柄。
EnsureHandle()
var hWnd = new WindowInteropHelper(Application.Current.MainWindow).EnsureHandle();
一旦应用程序启动,它将继续使用相同的句柄,没有问题。