Tuesday, May 09, 2006

In one of the hands-on labs here at MEDC a developer asked how to pass a managed funtion to a native DLL as a callback function.  I promised him a sample, so here's a simple one that shows how to call EnumWindows:

 

public delegate int EnumWindowsProc(IntPtr hwnd, IntPtr lParam);

public partial class Form1 : Form
{
    EnumWindowsProc callbackDelegate;
    IntPtr callbackDelegatePointer;

    [DllImport("coredll.dll", SetLastError = true)]
    public static extern bool EnumWindows(IntPtr lpEnumFunc, uint lParam);

    public Form1()
    {
        InitializeComponent();

        callbackDelegate = new EnumWindowsProc(EnumWindowsCallbackProc);
        callbackDelegatePointer = Marshal.GetFunctionPointerForDelegate(callbackDelegate);

        EnumWindows(callbackDelegatePointer, 0);
    }

    public int EnumWindowsCallbackProc(IntPtr hwnd, IntPtr lParam)
    {
        System.Diagnostics.Debug.WriteLine("Window: " + hwnd.ToString());

        return 1;
    }
}

5/9/2006 8:44:10 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
5/16/2006 9:50:31 AM (Eastern Daylight Time, UTC-04:00)
Thanks for the example. I am running into a little problem. I can't find the call GetFunctionPointerForDelegate() in my version of c# for Marshal. What do I need? I am using the Compact Framework.

Thanks in advance.
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):