在C#中使用API回呼函數的方法

來源:互聯網
上載者:User

在C#中使用API回呼函數的方法
就以EnumChildWindows和EnumChildProc為例子:

首先要聲明EnumChildProc 為一個回呼函數

public delegate bool EnumChildProc(int hwnd, IntPtr lParam);

delegate為C#中的回調類型,相當於C++裡面的CALLBACK,這樣就可以在下面聲明EnumChildWindows的時候在參數中使用EnumChildProc來作為一個類型。

聲明調用user32.dll中的EnumChildWindows,如下:

[DllImport("user32.dll", EntryPoint = "EnumChildWindows")]

public static extern bool EnumChildWindows(int hwndParent, EnumChildProc EnumFunc, IntPtr lParam);

定義一個和EnumChildProc傳回值和參數一樣的函數:

bool EnumCP(int hwnd,IntPtr lParam)

        {

            System.Text.StringBuilder sbClassName = new StringBuilder(255);

            GetClassName(hwnd, sbClassName, 255);

            if ("Static" == sbClassName.ToString())

            {                  

                return false;

            }

            return true;

        }

這時就可以使用EnumChildWindows(hwnd, EnumCP, IntPtr.Zero); 當EnumCP返回true的時候,EnumChildWindow繼續進行枚舉視窗。當EnumCP返回false的時候,EnumChildWindow停止進行枚舉視窗。

上面代碼實行的是當找到一個Static類的視窗後,停止枚舉。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.