触发控件的事件编程 [英] Trigger control's event programmatically
问题描述
假设我有一个WinFoms项目。只是有一个按钮(例如按钮1
)。
现在的问题是:是否有可能触发通过代码的 ButtonClicked
事件没有真正点击它
在.NET框架使用的模式,其中每一个事件的 X
有一个方法保护无效ONX(EventArgs的发送){}
引发事件的 X
。看到这个 MSDN文章。从声明类外引发一个事件,你将不得不派生类,并添加一个公共包装方法。在按钮
的情况下,它是这样的:
MyButton类:System.Windows.Forms.Button
{
公共无效ProgrammaticClick(EventArgs的发送)
{
base.OnClick(E);
}
}
Assume that I have a WinFoms project. There is just one button (e.g. button1
).
The question is: is it possible to trigger the ButtonClicked
event via code without really clicking it?
The .NET framework uses a pattern where for every event X
there is a method protected void OnX(EventArgs e) {}
that raises event X
. See this Msdn article. To raise an event from outside the declaring class you will have to derive the class and add a public wrapper method. In the case of Button
it would look like this:
class MyButton : System.Windows.Forms.Button
{
public void ProgrammaticClick(EventArgs e)
{
base.OnClick(e);
}
}
这篇关于触发控件的事件编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!