Windows Forms有一个属性win1.Handle,如果我没记错的话,它返回主窗口的句柄?
是否有一种相应的方法来获取WPF窗口的句柄?
我在网上找到了下面的代码,
IntPtr windowHandle =
new WindowInteropHelper(Application.Current.MainWindow).Handle;
但我认为那并没有帮助到我,因为我的应用程序有多个窗口。
Windows Forms有一个属性win1.Handle,如果我没记错的话,它返回主窗口的句柄?
是否有一种相应的方法来获取WPF窗口的句柄?
我在网上找到了下面的代码,
IntPtr windowHandle =
new WindowInteropHelper(Application.Current.MainWindow).Handle;
但我认为那并没有帮助到我,因为我的应用程序有多个窗口。
相比于传递 Application.Current.MainWindow
,只需传递对应窗口的引用: new WindowInteropHelper(this).Handle
等即可。
你可以使用WindowsInteropHelper类与窗口进行交互:
// ... Window myWindow = get your Window instance...
IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;
目前,您正在请求应用程序的主窗口,其中始终只会有一个。但是,只要它是 System.Windows.Window 派生的窗口类,您可以在任何窗口上使用相同的技术。
你可以使用:
Process.GetCurrentProcess().MainWindowHandle
在我的应用中,我需要在启动期间获取主窗口的句柄,但无论我怎么尝试,new WindowInteropHelper(...).Handle
都只会返回一个空句柄,因为窗口还没有被初始化。
您可以使用 EnsureHandle()
方法,它将创建句柄(如果不存在),或者返回当前的句柄(如果已存在)。
var hWnd = new WindowInteropHelper(Application.Current.MainWindow).EnsureHandle();
一旦应用程序启动,它会继续使用同一个句柄而没有任何问题。
如果您因某种原因需要获取应用程序所有窗口的窗口句柄,可以使用Application.Windows
属性获取所有窗口,然后像您已经演示的那样使用WindowInteropHandler
来获取它们的句柄。
在我的情况下,在OnLoaded()事件之后工作。在构造函数中,它会给出一个零句柄。
var winHandle = new WindowInteropHelper(this).Handle;