Wednesday, March 5, 2008

C# Platform Invoke Interop tip

Visual Basic 6.0 includes a tool called "API Text Viewer" that automatically generates method prototypes for win32 api methods.  These are generated for visual basic so they can't be directly used in C# but converting from the VB syntax to the C# syntax is often easier than converting directly from the native prototype.

e.g., the native signature for GetUserObjectInformation() is:

BOOL GetUserObjectInformation(
int nIndex,
PVOID pvInfo,
DWORD nLength,

the VB prototype:

Public Declare Function GetUserObjectInformation Lib 
"user32" Alias "GetUserObjectInformationA" (ByVal hObj As Long, ByVal nIndex As
Long, pvInfo As Any, ByVal nLength As Long, lpnLengthNeeded As Long) As

the C# prototype, at least for nIndex=2 (which gets the name of the object):


public static extern int
GetUserObjectInformaiton(int hObj, int nIndex, StringBuilder info, int nLength,
ref lengthNeeded)

A StringBuilder works here because when nIndex is 2 pvInfo will return a string.  Remember to initialize it with a max capacity equal to nLength (e.g., new StringBuilder(300, 300)).

No comments :

Post a Comment