Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Win32

Use Lambda Expressions as Unmanaged Callbacks

4.40/5 (5 votes)
5 Nov 2010CPOL 5.9K  
// Even more simplifiedclass Program{ [DllImport(user32, ExactSpelling = true)] static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, IntPtr lParam); [UnmanagedFunctionPointer(CallingConvention.Winapi)] delegate bool WNDENUMPROC(IntPtr hwnd, IntPtr lParam); ...
C#
// Even more simplified
class Program
{
    [DllImport("user32", ExactSpelling = true)]
    static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, IntPtr lParam);

    [UnmanagedFunctionPointer(CallingConvention.Winapi)]
    delegate bool WNDENUMPROC(IntPtr hwnd, IntPtr lParam);

    static void Main(string[] args)
    {
        List<IntPtr> windows = new List<IntPtr>();
        EnumWindows((hwnd, lParam) =>
        {
            windows.Add(hwnd);
            return true;
        }, IntPtr.Zero);
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)