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:
-
http://www.pocketpcdn.com/sections/dotnet.html
Section: .NET CF
-
http://www.pocketpcdn.com/articles/dotnetcf_okbtn.html
QA: How to hide the OK button in the dialog in .Net Compact Framework application?
-
http://www.pocketpcdn.com/articles/dotnetcf_multiwin.html
QA: How to avoid multiple entries in the task list for the .Net application?