Getting the Windows System Error Code title/description from its hex number

I’m not sure if there’s a niifty .NET wrapper, but you could call the FormatMessage API using P/Invoke. See this answer for how it would normally be called from native code. Though the question refers to grabbing error codes from HRESULTs, the answer also applies for retreiving codes from the regular OS error codes coming … Read more

Is there a tool that generates P/Invoke signatures for arbitrary unmanaged DLL?

Google quickly found http://www.pinvoker.com (Wayback) (Compatiblity listed as VS2005, 2008, and 2010; it doesn’t seem to have been updated to work with newer versions) Microsoft’s C++/CLI compiler can also do this, if you use /clr:safe and #include the header file, it will generate p/invoke code which you can extract with e.g. ILSpy (free) or Red … Read more

Correct way (in .NET) to switch the focus to another application

Get the window handle (hwnd), and then use this user32.dll function: VB.net declaration: Declare Function SetForegroundWindow Lib “user32.dll” (ByVal hwnd As Integer) As Integer C# declaration: [DllImport(“user32.dll”)] public static extern int SetForegroundWindow(int hwnd) One consideration is that this will not work if the window is minimized, so I’ve written the following method which also handles … Read more

PInvoke for C function that returns char *

You must return this as an IntPtr. Returning a System.String type from a PInvoke function requires great care. The CLR must transfer the memory from the native representation into the managed one. This is an easy and predictable operation. The problem though comes with what to do with the native memory that was returned from … Read more

Profiling a dynamic pinvoke

The profiler APIs are returning metadata specified in the managed code, normally via the DllImportAttribute. In the case of the ‘dynamic pinvoke’ which uses the Marshal.GetDelegateForFunctionPointer method, the module and function names were never specified as metadata and not available. An alternative approach to dynamic pinvoke declarations that includes the required metadata will probably avoid … Read more