Finding the handle to a WPF window

WpfWindowHandle

Wpf Problem Overview


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

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

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!!

Wpf Solutions


Solution 1 - Wpf

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

Solution 2 - Wpf

Just use your window with the WindowsInteropHelper class:

// ... 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.

Solution 3 - Wpf

you can use :

Process.GetCurrentProcess().MainWindowHandle

Solution 4 - Wpf

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

Solution 5 - Wpf

In my use case I needed a handle to the main window during startup, and no matter what I did I couldn't get new WindowInteropHelper(...).Handle to return anything other than a null handle since the window hadn't been initialized yet.

You can use the EnsureHandle() method instead, which will create the handle if it doesn't already exist, or return the current one if it does exist.

var hWnd = new WindowInteropHelper(Application.Current.MainWindow).EnsureHandle();

Once the application has started, it continues using the same handle without issue.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEvanView Question on Stackoverflow
Solution 1 - WpfGregory HigleyView Answer on Stackoverflow
Solution 2 - WpfReed CopseyView Answer on Stackoverflow
Solution 3 - WpfAmer SawanView Answer on Stackoverflow
Solution 4 - WpfdustyburwellView Answer on Stackoverflow
Solution 5 - WpfradjView Answer on Stackoverflow