这是一本C#书 . 我不明白的是,对于这是一个回调,不应该从user32.dll调用PrintWindow的EnumWindow . 也许,我不是理解代表或正确回调 . 请帮我理解 .

来自非托管代码的回调

P / Invoke层尽力在边界的两侧呈现自然编程模型,在可能的情况下在相关构造之间进行映射 . 由于C#不仅可以调用C函数,还可以从C函数调用(通过函数指针),因此P / Invoke层将非托管函数指针映射到C#中最近的等价函数,即C代理 .

例如,您可以在User32.dll中使用此方法枚举所有顶级窗口句柄:

BOOL EnumWindows (WNDENUMPROC lpEnumFunc, LPARAM lParam);

     WNDENUMPROC is a callback that gets fired with the handle of each window in sequence (or until the callback returns false). Here is its definition:

BOOL CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam);

要使用它,我们声明一个具有匹配签名的委托,然后将委托实例传递给外部方法:

using System;
 using System.Runtime.InteropServices;

 class CallbackFun
{
    delegate bool EnumWindowsCallback (IntPtr hWnd, IntPtr lParam);

   [DllImport("user32.dll")]
   static extern int EnumWindows (EnumWindowsCallback hWnd, IntPtr lParam);

   static bool PrintWindow (IntPtr hWnd, IntPtr lParam)
   {
        Console.WriteLine (hWnd.ToInt64());
        return true;
    }

    static void Main()
    {
        EnumWindows (PrintWindow, IntPtr.Zero);
    }
 }