简体   繁体   English

当事件处理程序是委托并且不包含该参数时,如何将参数传递给事件处理程序?

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

I have a method as follows:我有一个方法如下:

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);
        }

i want to take action from user and pass into hwndSourceHook method:我想从用户那里采取行动并传递给 hwndSourceHook 方法:

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

but i dont know how to do this但我不知道该怎么做

hwndSourceHook has a specific signature that you can't change, which means you can't add a parameter to its signature. hwndSourceHook具有您无法更改的特定签名,这意味着您无法在其签名中添加参数。 You can only pass an event handler to hWndSource.AddHook that matches the signature您只能将事件处理程序传递给与签名匹配的hWndSource.AddHook

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

One option is to use an anonymous function instead of declaring a separate method for your handler, like this:一种选择是使用匿名 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);
}

Instead of putting the event handler in a separately declared method we're declaring it inline within RegisterToMethod .我们没有将事件处理程序放在单独声明的方法中,而是在RegisterToMethod内内联声明它。 That allows us to include the parameter passed to the outer method.这允许我们包含传递给外部方法的参数。

This is called a closure .这称为闭包

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM