61

My WPF application has more than one window, I need to be able to get the hWnd of each Window instance so that I can use them in Win32 API calls.

Example of what I would like to do:

Window myCurrentWindow = Window.GetWindow(this);
IntPtr myhWnd = myCurrentWindow.hWnd; // Except this property doesn't exist.

What's the best way to do this?

Drahcir
  • 11,772
  • 24
  • 86
  • 128
  • 2
    possible duplicate of [Is it possible to get the Hwnd of a WPF Popup control?](http://stackoverflow.com/questions/7815121/is-it-possible-to-get-the-hwnd-of-a-wpf-popup-control) – Hans Passant May 20 '12 at 17:05
  • 2
    @HansPassant: The other question concerned popup controls, not actual windows. (Yes, this question was also indirectly answered within it, but it is not a duplicate.) – Douglas May 20 '12 at 17:08

2 Answers2

92

WindowInteropHelper is your friend. It has a constructor that accepts a Window parameter, and a Handle property that returns its window handle.

Window window = Window.GetWindow(this);
var wih = new WindowInteropHelper(window);
IntPtr hWnd = wih.Handle;
Douglas
  • 53,759
  • 13
  • 140
  • 188
24

Extending on Douglas's answer, if the Window has not been shown yet, it might not have an HWND. You can force one to be created before the window is shown using EnsureHandle():

var window = Window.GetWindow(element);

IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();

Note that Window.GeWindow can return null, so you should really test that too.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • I feel like the checks would rarely be needed, generally you'd just place your code where you're sure the window handle exists. The most obvious would be the Loaded event – MikeKulls Mar 21 '22 at 12:31