Calling a Win32 dll function

suggest change
using System.Runtime.InteropServices;

class PInvokeExample
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint options);

    public static void test()
    {
        MessageBox(IntPtr.Zero, "Hello!", "Message", 0);
    }
}

Declare the function as static extern and set DllImportAttribute to the DLL name. Import the System.Runtime.InteropServices namespace, then call it as a regular static method.

Platform Invocation Services loads the DLL and finds the function. In simple cases, P/Invoke also marshals parameters and the return value (converting between .NET and Win32 types).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents