Click here to Skip to main content
15,881,600 members
Articles / Desktop Programming / Win32
Tip/Trick

Use Lambda Expressions as Unmanaged Callbacks

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
7 Nov 2010CPOL 17.4K   1   1
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)


Written By
Software Developer
Japan Japan
In 1985, I got my first computer Casio MX-10, the cheapest one of MSX home computers. Then I began programming in BASIC and assembly language, and have experienced over ten languages from that time on.
Now, my primary languages are C++ and C#. Working for a small company in my home town in a rural area of Japan.


Comments and Discussions

 
GeneralThis would indeed be needlessly complex if everything was pl... Pin
E.F. Nijboer5-Nov-10 9:44
E.F. Nijboer5-Nov-10 9:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.