Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the hWnd of Window instance?

Tags:

c#

wpf

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?

like image 789
Drahcir Avatar asked May 20 '12 16:05

Drahcir


People also ask

How do I get HWND of a window in Python?

If you want to get window handles you can use with win32gui , use win32gui. EnumWindows instead of calling the raw function out of the user32 DLL.

How can I get Hwnd from process id?

You can use EnumWindows and GetWindowThreadProcessId() functions as mentioned in this MSDN article.

What is window Hwnd?

HWND is a "handle to a window" and is part of the Win32 API . HWNDs are essentially pointers (IntPtr) with values that make them (sort of) point to a window-structure data. In general HWNDs are part an example for applying the ADT model. If you want a Control's HWND see Control.

How do I find my window handles?

The Win32 API provides no direct method for obtaining the window handle associated with a console application. However, you can obtain the window handle by calling FindWindow() . This function retrieves a window handle based on a class name or window name. Call GetConsoleTitle() to determine the current console title.


2 Answers

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;
like image 175
Douglas Avatar answered Oct 18 '22 03:10

Douglas


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.

like image 42
Drew Noakes Avatar answered Oct 18 '22 03:10

Drew Noakes