C# 如何以编程方式调用事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/495826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I programmatically invoke an event?
提问by
I am creating a C# Windows Mobile application that I need to programmatically invoke the click event on a Button.
我正在创建一个 C# Windows Mobile 应用程序,我需要以编程方式调用按钮上的单击事件。
I have looked at the Button class and do not see a way to do this.
我已经查看了 Button 类,但没有看到这样做的方法。
采纳答案by Anton Gogolev
You might consider changing your design: at least move the logic from button1_Click handler somewhere else so that you'll be able to invoke it from wherever you want.
您可能会考虑更改您的设计:至少将 button1_Click 处理程序中的逻辑移到其他地方,以便您可以从任何地方调用它。
回答by Sergio
Anything that prevents you from simply invoking the method that handles the onClick event?
有什么可以阻止您简单地调用处理 onClick 事件的方法吗?
回答by BFree
You can do something like this:
你可以这样做:
private void button1_Click(object sender, EventArgs e)
{
OnButtonClick();
}
private void OnButtonClick()
{
}
Then you can call your OnButtonClick()
wherever you need to.
然后你可以在OnButtonClick()
任何你需要的地方打电话给你。
回答by Greg Ogle
Not exactly the answer you were probably looking for:::
不完全是您可能正在寻找的答案:::
You might just call the code you want to run, move the meat of the code outside the OnClick handling method. The OnClick method could fire that method the same as your code.
您可能只是调用要运行的代码,将代码的主要内容移到 OnClick 处理方法之外。OnClick 方法可以像您的代码一样触发该方法。
回答by Exulted
The Control class, from which Button inherits, has the OnClick method, which invokes the Click event. Using reflection, you can call this method, even though it is declared protected. For instance, I created the following extension method:
Button 从其继承的 Control 类具有调用 Click 事件的 OnClick 方法。使用反射,您可以调用此方法,即使它声明为受保护。例如,我创建了以下扩展方法:
public static void PerformClick(this Control value)
{
if (value == null)
throw new ArgumentNullException();
var methodInfo = value.GetType().GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(value, new object[] { EventArgs.Empty });
}
Although, this may be regarded as a dirty hack...
虽然,这可能被视为肮脏的黑客......
回答by Funkky Exalter
You can call the added event handler function as:
您可以将添加的事件处理函数调用为:
someControl_EventOccured(someControl, new EventArgs());
This works when the control's event argument e
is not used inside the handler function, and mostly it's not used.
这e
在处理程序函数中未使用控件的事件参数时有效,并且大多数情况下未使用。