winformsvisual-studiovisual-c++handle

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


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


Solution

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

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

    Works.