Finding the handle to a WPF window

Viewed 116140

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.

5 Answers

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.

Related