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.50/5 (2 votes)
7 Nov 2010CPOL 17.7K  
An application of lambda expressions to simplify your code.
Unmanaged functions often require callback functions, and we sometimes have to call such functions from C# program. This is a sample which calls EnumWindows without lambda.

C#
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 List<IntPtr> windows;
    
    static bool WndEnumCallback(IntPtr hwnd, IntPtr lParam)
    {
        windows.Add(hwnd);
        return true;
    }

    static void Main(string[] args)
    {
        windows = new List<IntPtr>();
        EnumWindows(new WNDENUMPROC(WndEnumCallback), IntPtr.Zero);
        // Some work using window handles.
    }
}


You should promote a code block cannot be reused to a member method, and a mere temporary variable to a field. It makes your code needlessly complex. Since C# 3.0, you can use a lamdba expression to simplify it.

C#
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

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>();
        WNDENUMPROC callback = (hwnd, lParam) =>
        {
            windows.Add(hwnd);
            return true;
        };

        EnumWindows(callback, IntPtr.Zero);

        // Some work using window handles.
    }
}


In this code, you can define a temporary variable and a non-reusable code block as local variables.

License

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