Implement the callback function (zz)

Source: Internet
Author: User
Implement callback Functions

Http://msdn.microsoft.com/library/chs/default.asp? Url =/library/CHS/cpguide/html/cpconusingcallbackfunctions. asp

A callback function is the code that helps an unmanaged DLL function to complete a task in a hosted application. The call to the callback function is indirectly passed to the hosted implementation through a DLL function in the hosted application. Among the various DLL functions called by the platform, some functions require that the callback functions in managed code be correctly run. This topic describes the elements of managed functions and describes how to implement callback functions and call callback functions from managed code.

Callback Function Basics

To call most DLL functions from managed code, you can create managed definitions for the function and then call the function. This process is straightforward.

To use the DLL function that requires a callback function, there are some additional steps. First, you must check the function in the document to determine whether the function requires callback. Then, you must create a callback function in the hosted application. Finally, call the DLL function and pass the pointer pointing to the callback function as a parameter. These steps are summarized.

Callback functions and implementation

Callback functions are ideal for repeated task execution. Another common purpose is to work with enumeration functions (such asEnumfontfamilies,EnumprintersAndEnumwindows. The example in the following section is as follows,EnumwindowsThe function will enumerate all existing windows on the computer and call the callback function to execute a task for each window.

Implement callback Functions

The following process describes how managed applications use Platform calls to output the handle values for each window on the local computer. In particular, the example usesEnumwindowsFunction to gradually browse the window list, and use a managed callback function (called callback) to output the value of the window handle.

Implement callback Functions

  1. ViewEnumwindowsFunction signature.EnumwindowsHas the following signature:
    BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam)

    Indicates that one of the clues for callback of this function exists.LpenumfuncParameters. If the parameter uses a pointer to the callback function, its name usually includesLp(Long pointer) prefix andFuncSuffix combination. For more information about Win32 functions, see Microsoft platform SDK.

  2. Create a managed callback function. This example declaresCallBackThe delegate type, which uses two parameters:HwndAndLparam. The first parameter is the window handle, and the second parameter is defined by the application. In this version, both parameters must be integers.

    The callback function usually returns a non-zero value to indicate success, and returns zero to indicate failure. In this example, the return value is explicitly setTrueTo continue enumeration.

  3. Create a delegate and pass it as a parameterEnumwindowsFunction. Platform calls automatically convert delegates to common callback formats.
  4. Make sure that the garbage collector does not recycle the delegate before the callback function completes its work. If the delegate is passed as a parameter, or the contained delegate is passed as a field in the structure, the Delegate will not be recycled during the call. Therefore, as shown in the following enumeration example, the callback function completes its work before the call returns, without the need to host the caller to perform additional operations.

    However, if the callback function can be called after the callback function is returned, the hosted caller must take appropriate measures to ensure that the delegate will not be recycled until the callback function completes its work. For more information about how to prevent garbage collection, see use Platform calls to handle InterOP messages.

Example

[Visual Basic]Imports SystemImports System.Runtime.InteropServicesPublic Delegate Function CallBack( _hwnd As Integer, lParam As Integer) As BooleanPublic Class EnumReportApp    Declare Function EnumWindows Lib "user32" ( _       x As CallBack, y As Integer) As Integer    Public Shared Sub Main()        EnumWindows(AddressOf EnumReportApp.Report, 0)    End Sub 'Main    Public Shared Function Report(hwnd As Integer, lParam As Integer) _    As Boolean        Console.Write("Window handle is ")        Console.WriteLine(hwnd)        Return True    End Function 'ReportEnd Class 'EnumReportApp[C#]using System;using System.Runtime.InteropServices;public delegate bool CallBack(int hwnd, int lParam);public class EnumReportApp {    [DllImport("user32")]    public static extern int EnumWindows(CallBack x, int y);     public static void Main()     {        CallBack myCallBack = new CallBack(EnumReportApp.Report);        EnumWindows(myCallBack, 0);    }   public static bool Report(int hwnd, int lParam) {         Console.Write("Window handle is ");        Console.WriteLine(hwnd);        return true;    }}[C++]using namespace System::Runtime::InteropServices;// A delegate type.__delegate bool CallBack(int hwnd, int lParam);// Managed type with the method to call.__gc class EnumReport {// Report the window handle.public:    bool Report(int hwnd, int lParam) {       Console::Write(L"Window handle is ");       Console::WriteLine(hwnd);       return true;   }};[DllImport("user32")] extern "C" int EnumWindows(CallBack* x, int y); void main(void) {     EnumReport* er = new EnumReport;    CallBack* myCallBack = new CallBack(er, &EnumReport::Report);    EnumWindows(myCallBack, 0); }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.