Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 963
mring Avatar asked May 16 '12 15:05

mring


People also ask

How do you get 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.

What is IntPtr handle?

This is typically referring to an operating system Handle, and used internally. For example, Windows Forms uses an IntPtr to refer to the Control's native Window Handle (HWND).

Is Hwnd a pointer?

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.


1 Answers

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

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

Works.

like image 50
mring Avatar answered Nov 16 '22 01:11

mring