问题描述
我有一个第三方编辑器,它基本上包含一个文本框和一个按钮(DevExpress ButtonEdit 控件).我想让特定的击键 (Alt + Down) 模拟单击按钮.为了避免一遍又一遍地写这个,我想制作一个通用的 KeyUp 事件处理程序,它将引发 ButtonClick 事件.不幸的是,控件中似乎没有引发 ButtonClick 事件的方法,所以...
I have a third-party editor that basically comprises a textbox and a button (the DevExpress ButtonEdit control). I want to make a particular keystroke (Alt + Down) emulate clicking the button. In order to avoid writing this over and over, I want to make a generic KeyUp event handler that will raise the ButtonClick event. Unfortunately, there doesn't seem to be a method in the control that raises the ButtonClick event, so...
如何通过反射从外部函数引发事件?
How do I raise the event from an external function via reflection?
推荐答案
这是一个使用泛型的演示(省略了错误检查):
Here's a demo using generics (error checks omitted):
using System;
using System.Reflection;
static class Program {
private class Sub {
public event EventHandler<EventArgs> SomethingHappening;
}
internal static void Raise<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs
{
var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source);
if (eventDelegate != null)
{
foreach (var handler in eventDelegate.GetInvocationList())
{
handler.Method.Invoke(handler.Target, new object[] { source, eventArgs });
}
}
}
public static void Main()
{
var p = new Sub();
p.Raise("SomethingHappening", EventArgs.Empty);
p.SomethingHappening += (o, e) => Console.WriteLine("Foo!");
p.Raise("SomethingHappening", EventArgs.Empty);
p.SomethingHappening += (o, e) => Console.WriteLine("Bar!");
p.Raise("SomethingHappening", EventArgs.Empty);
Console.ReadLine();
}
}
这篇关于如何通过 .NET/C# 中的反射引发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!