QA: How to obtain the window handle of the .Net control?

Andrey Lebedev (andrey.lebedev@softspb.com), October 31, 2003.

Question

I want to call WinAPI function and I need HWND of my control for that. How to obtain the window handle of the .Net control?

Answer

Here is a simple trick to obtain the window handle of a .Net window or control. You set the capture to the .Net window using .Net capabilities and then you get the window handle of the window that has the capture using Windows API. The idea is implemented in the following GetHWnd function:

class WinAPI { [DllImport("coredll.dll")] private static extern IntPtr SetCapture(IntPtr hWnd); [DllImport("coredll.dll")] private static extern IntPtr GetCapture(); public static IntPtr GetHWnd(Control ctrl) { IntPtr hOldWnd = GetCapture(); ctrl.Capture = true; IntPtr hWnd = GetCapture(); ctrl.Capture = false; SetCapture(hOldWnd); return hWnd; } }

The usage of the GetHWnd function is simple:

IntPtr hWndButton = WinAPI.GetHWnd(button1);

Done!

Related resources: