May 07
This is one of those things that’s obvious once you know it. When dealing with COM, there is often a need to convert a WinForms Form object to an IntPtr handle, and vice versa.
Convert Handle to Form
static public Form GetForm( IntPtr handle ) { return handle == IntPtr.Zero ? null : Control.FromHandle( handle ) as Form; }
Convert Form to Handle
Form form = new Form(); IntPtr handle = form.Handle;
I am curious to find out what blog platform you’re using? I’m having some minor security problems with my latest website and I would like to find something more safe. Do you have any solutions? Hmm it looks like your blog ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I too am an aspiring blog blogger but I’m still new to everything. Do you have any points for newbie blog writers? I’d certainly appreciate it.
While it’s perfectly valid to use Form.Handle to get the IntPtr window handle, it’s probably not good to include the
Form form = new Form();
in the previous line without mentioning the inner workings of creating a handle – it’s far from trivial how that occurs and forcing a handle to be created immediately after calling the Form c’tor is far from best practice. The property Control.IsHandleCreated wouldn’t exist if it was trivial.
Normally, a reference to a Control.Handle shouldn’t be kept in an application but rather used for “immediate consumption” i.e. use it to find out if your window is the active window.
Really instructive and great structure of written content , now that’s user genial (:.