I need the intPtr for a form. Control.FromHandle(control) gives me the control from a handle, but I need the opposite--get the handle from a control. How do I do this?
+4
A:
Try
Dim handle As IntPtr = someControl.Handle
Note: This will only work after the Handle for the control is created. There is a window of time in between when you create a control and when it is rendered to some degree where this may return IntPtr.Zero
JaredPar
2009-05-08 18:08:56
Duh, thanks. Works great! Appreciate it.
Jeff
2009-05-08 18:12:02
+1
A:
Note: This will only work after the Handle for the control is created. There is a window of time in between when you create a control and when it is rendered to some degree where this may return IntPtr.Zero
I have to disagree with JaredPar on this : the get accessor of the Handle property calls CreateHandle if the handle is not yet created (you can check with Reflector). It's important to be aware of that because in some cases it could have unexpected consequences
Thomas Levesque
2009-05-08 18:29:59
Check the method in reflector. There are cases where it simply will not create a handle. It is not guaranteed to happen but can happen under certain configuration.
JaredPar
2009-05-08 18:31:40
I must confess I had not analyzed the code of the CreateHandle method... now that I did, I find it a little confusing, and I'm not sure it always creates the handle. So maybe you're right eventually ;)
Thomas Levesque
2009-05-08 18:47:40
@Thomas, there is a far out corner case where the underlying state prevents handle creation. I only know it exists because I've hit it before because I assumed Handle will be valid before being disposed. Been ~2 years so I can't remember the details (only the pain :) ).
JaredPar
2009-05-08 18:53:20