Calling a Win32 dll function

suggest change
using System.Runtime.InteropServices;

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

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

Declare a function as static extern stting DllImportAttribute with its Value property set to .dll name. Don’t forget to use System.Runtime.InteropServices namespace. Then call it as an regular static method.

The Platform Invocation Services will take care of loading the .dll and finding the desired finction. The P/Invoke in most simple cases will also marshal parameters and return value to and from the .dll (i.e. convert from .NET datatypes to Win32 ones and vice versa).

Feedback about page:

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

Table Of Contents