Convert an IntPtr window handle to IWin32Window^

2019-02-08 04:59发布

问题:

How do I convert a handle acquired from a form/control's Handle property, to a IWin32Window^ ?

回答1:

Control.FromHandle

(That gets you the Control object, which implements the IWin32Window interface.)

Eg.

IntPtr myWindowHandle = IntPtr(someVal);
IWin32Window^ w = Control::FromHandle(myWindowHandle);

Note that this relies on the handle being "acquired from a form/control's Handle property." You cannot use this technique with an arbitrary Win32 window handle.



回答2:

There's a simpler method that is supported directly by the .NET framework without having to create your own custom class. You can use this with any arbitrary Window handle.

Given ptrWindowHandle of type IntPtr:

using System.Windows.Forms;

NativeWindow nativeWindow = new NativeWindow();
nativeWindow.AssignHandle(ptrWindowHandle);

System.Windows.Forms.NativeWindow implements the IWin32Window interface.



回答3:

This appears to be exactly what you are asking for. I've never done it myself, but it appears to be relatively straightforward:

Creating a IWin32Window from a Win32 Handle

Good luck!