簡體   English   中英

當事件處理程序是委托並且不包含該參數時,如何將參數傳遞給事件處理程序?

[英]How do I pass an argument to an event handler when the event handler is a delegate and doesn't include that argument?

我有一個方法如下:

public static void RegisterForMessage(System.Windows.Window window, Action action)
        {
            HwndSource hWndSource;
            WindowInteropHelper wih = new WindowInteropHelper(window);
            hWndSource = HwndSource.FromHwnd(wih.Handle);
            hWndSource.AddHook(hwndSourceHook);
        }

我想從用戶那里采取行動並傳遞給 hwndSourceHook 方法:

private static IntPtr hwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            // Action must be run here
            return IntPtr.Zero;
        }

但我不知道該怎么做

hwndSourceHook具有您無法更改的特定簽名,這意味着您無法在其簽名中添加參數。 您只能將事件處理程序傳遞給與簽名匹配的hWndSource.AddHook

public delegate IntPtr HwndSourceHook(
    IntPtr hwnd, 
    int msg, 
    IntPtr wParam, 
    IntPtr lParam, 
    ref bool handled);

一種選擇是使用匿名 function 而不是為您的處理程序聲明一個單獨的方法,如下所示:

public static void RegisterForMessage(System.Windows.Window window, Action action)
{
    HwndSource hWndSource;
    WindowInteropHelper wih = new WindowInteropHelper(window);
    hWndSource = HwndSource.FromHwnd(wih.Handle);
    HwndSourceHook eventHandler = (IntPtr hwnd, 
                                   int msg, 
                                   IntPtr param, 
                                   IntPtr lParam, 
                                   ref bool handled) =>
    {
        action.Invoke();
        return IntPtr.Zero;
    };
    hWndSource.AddHook(eventHandler);
}

我們沒有將事件處理程序放在單獨聲明的方法中,而是在RegisterToMethod內內聯聲明它。 這允許我們包含傳遞給外部方法的參數。

這稱為閉包

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM