October 30, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Using Delegates with Native Function Callbacks in Managed C++

  • June 8, 2005
  • 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);

[DllImport("user32")] 
extern "C" int EnumWindows(EnumWindowsCallback* callback, int lParam); 

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

__gc class WindowLister
{
public:
  static void EnumWindows()
  {
    EnumWindowsCallback* cb = 
      new EnumWindowsCallback(NULL, &__EnumWindows);
    ::EnumWindows(cb,0);
  }
protected:
  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()
{
  WindowLister::EnumWindows();
  return 0;
}

Download the Code

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

Acknowledgements

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



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel