When working with window handles, is it good enough to use the plain IntPtr or should I subclass SafeHandle?
Are there any significant pros/cons?
Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I wouldn’t think that
SafeHandlewould add any value. MSDN provides the following remarks on the usage ofSafeHandles (emphasis mine):Neither of these two goals seems applicable to a window handle returned from a Windows Forms
Controlobject. Handle recycling seems moot given typical usages of aControl‘sHandleproperty, and the framework and the operating system take any finalization issues out of your hands with window handles.Another way to think of it is this: to use
SafeHandle, you’d have to provide an implementation for theIsInvalidproperty and theReleaseHandlemethod. TheControl.Handleproperty will never, to my knowledge, return an invalid value, and the window handle will be and should only be ‘released’ when the control is disposed.That said, the framework itself does wrap window handles in a
HandleRefobject when it uses them, which simply protects the control from the garbage collector while the handle is being used by unmanaged code. This is something you’re unlikely to need in the typical scenarios you’d need a window handle, but it takes almost no work to use it, if there’s a possibility you might need it.