How to implement safehandle for an Intptr variable
-
Thursday, January 05, 2006 1:01 PM
We are working on customization of Word 2003 using VSTO 2005. To handle keyboard events we implemented keyhooks.
In keyhooks class we used a variable named keyHook of type Intptr.When we run code analysis tool the following error is coming.
"CA2006 : Microsoft.Reliability : Review usage of 'localHook' (a System.IntPtr instance) to determine whether it should be replaced with a SafeHandle or CriticalHandle"
Tried with samples given by some links, but they are not really helping.Any pointers would be greatly appreciated.
Basically i need to implement handle for the localhook variable.
All Replies
-
Thursday, January 05, 2006 3:56 PMModerator
What the rule is telling you is that using an IntPtr doesn't guarantee that your unmanaged pointer will be properly cleaned up in the face of exceptions. You should change the type of your keyhook variable to SafeHandle instead. This may impact other areas of your code. SafeHandle has a constructor that accepts the IntPtr as a parameter.
Michael Taylor - 1/5/06
-
Thursday, January 05, 2006 4:57 PM
Note that SafeHandle is an abstract class. So you'll have to inherit from it to create your own. Also note that the constructor actually is expecting an IntPtr that would be considered invalid. You might want to look at the documentation here: System.Runtime.InteropServices.SafeHandle and look at how it's done. Here's another reference that might help: http://blogs.msdn.com/bclteam/archive/2005/03/15/396335.aspx
hope that helps,
Imran.

