How to get a HWND handle out of a System.Windows.Forms.Form

mring picture mring · May 16, 2012 · Viewed 19.6k times · Source

Given the form

System.Windows.Forms::Form Form1;

and the window handle

HWND hWnd;

How can I set hWnd to the Handle property of Form1 that does truly exist as a public property that "Gets the window handle that the control is bound to. (Inherited from Control.)" according to the Microsoft documentation of System.Windows.Forms::Form? In the constructor of my Form Form1, I've tried

hWnd = this.Handle;

but the compiler complains:

error C2228: left of '.Handle' must have class/struct/union type is 'MyNamespace::Form1 ^const ' did you intend to use '->' instead?

So I try

hWnd = this->Handle;

and just

hWnd = Handle; // Since I'm in the Form

and then the compiler says:

error C2440: '=' : cannot convert from 'System::IntPtr' to 'HWND' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Answer

mring picture mring · May 16, 2012

I found a solution, and don't care if it's a kludge.

hWnd = static_cast<HWND>(Handle.ToPointer());

Works.