July 8, 2020
Hot Topics:

Using Delegates with Native Function Callbacks in Managed C++

  • By Tom Archer
  • Send Email »
  • More Articles »

Native Callback Function Example

Using the EnumWindows function as an example, here's a very simple Managed C++ class that exposes a static method to enumerate all the open windows on your system:
__delegate bool EnumWindowsCallback(IntPtr hwnd, IntPtr lParam);

extern "C" int EnumWindows(EnumWindowsCallback* callback, int lParam); 

extern "C" int GetWindowText(IntPtr hwnd, char title[], int nMaxCount );

__gc class WindowLister
  static void EnumWindows()
    EnumWindowsCallback* cb = 
      new EnumWindowsCallback(NULL, &__EnumWindows);
  static bool __EnumWindows(IntPtr hwnd, IntPtr lParam)
    char title[201];
    int c = ::GetWindowText(hwnd, title, 200);
    if (c > 0) Console::WriteLine(title);

    return true;

Note that the method also calls the GetWindowText Win32 API function (which also has to imported), so as to display a more user-friendly name for the window (as opposed to its hwnd value).

Now that the Win32 EnumWindows function is encapsulated in the WindowLister class, calling it as simple as follows:

int _tmain()
  return 0;

Download the Code

To download the accompanying source code for the example, click here.


Many thanks to , who is one of the most knowledgeable people in the world on pretty much everything associated with Managed C++ and .NET programming. James introduced me to this technique (and many others) when he, Nishant Sivakumar, and I wrote Extending MFC Applications with the .NET Framework.

About the Author

Tom Archer owns his own training company, Archer Consulting Group, which specializes in educating and mentoring .NET programmers and providing project management consulting. If you would like to find out how the Archer Consulting Group can help you reduce development costs, get your software to market faster, and increase product revenue, contact Tom through his Web site.

Page 2 of 2

This article was originally published on June 8, 2005

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date