15.4 Call an Unmanaged Function That Uses a Callback


Problem

You need to call an unmanaged function and allow it to call a method in your code.

Solution

Create a delegate that has the required signature for the callback. Use this delegate when defining and using the unmanaged function.

Discussion

Many of the Win32 API functions use callbacks. For example, if you want to retrieve the name of all the windows that are currently open , you can call the unmanaged EnumWindows function in the User32.dll file. When calling EnumWindows , you need to supply a pointer to a function in your code. The Windows operating system will then call this function repeatedly, once for each window that it finds, and pass the window handle to your code.

The .NET Framework allows you to handle callback scenarios like this without resorting to pointers and unsafe code blocks. Instead, you can define and use a delegate that points to your callback function. When you pass the delegate to the EnumWindows function, for example, the CLR will automatically marshal the delegate to the expected unmanaged function pointer.

Following is a console application that uses EnumWindows with a callback to display the name of every open window.

 using System; using System.Text; using System.Runtime.InteropServices; public class GetWindows {     // The signature for the callback method.     public delegate bool CallBack(int hwnd, int lParam);         // The unmanaged function that will trigger the callback     // as it enumerates the open windows.     [DllImport("user32.dll")]     public static extern int EnumWindows(CallBack callback, int param);          [DllImport("user32.dll")]     public static extern int GetWindowText(int hWnd, StringBuilder lpString,        int nMaxCount);         private static void Main() {         CallBack callBack = new CallBack(DisplayWindowInfo);         // Request that the operating system enumerate all windows,         // and trigger your callback with the handle of each one.          EnumWindows(callBack, 0);         Console.ReadLine();     }         // The method that will receive the callback. The second      // parameter is not used, but is needed to match the      // callback's signature.     public static bool DisplayWindowInfo(int hWnd, int lParam) {          int chars = 100;         StringBuilder buf = new StringBuilder(chars);         if (GetWindowText(hWnd, buf, chars) != 0) {             Console.WriteLine(buf);         }         return true;     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net