简体   繁体   English

手动触发事件C#

[英]Manual triggering of events c#

I have a button that when clicked displays some information, can i manually trigger the button clicked event in code ? 我有一个按钮,当单击该按钮时会显示一些信息,我可以手动触发代码中的按钮单击事件吗?

I need this so that when i click on some other button it automatically triggers this event too. 我需要这样做,以便当我单击其他按钮时,它也会自动触发此事件。

A good way would be to have NO code (except a method/function call) in an event handler. 一个好的方法是在事件处理程序中不包含任何代码(方法/函数调用除外)。 this would made it possible to call it from any place in your program. 这样就可以从程序的任何位置调用它。

移动代码以响应单击按钮的功能,然后在事件处理程序和另一个事件处理程序中调用该功能。

You can do it like this. 您可以这样做。

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("button1");
}

private void button2_Click(object sender, EventArgs e)
{
    MessageBox.Show("button2");
    button1_Click(sender, e);
}

如果您不关心发件人或EventArgs,也可以使用

Button1_Click(null, new EventArgs());

您可以使用Button.PerformClick()

There are two ways to do this, 有两种方法可以做到这一点,

1# -= Move the code which you have written in the button click event to another function and call this function in this button click event and in other button click event also. 1#-=将您在按钮单击事件中编写的代码移至另一个函数,并在此按钮单击事件中以及在其他按钮单击事件中调用此函数。

2# - For the second button click event specify the first button click event as the event handler. 2#-对于第二个按钮单击事件,将第一个按钮单击事件指定为事件处理程序。

3# - call button1's event handler inside button2. 3#-在button2内调用button1的事件处理程序。

private void button2_Click(object sender, EventArgs e)
{
    button1_Click(sender, e);
}

I will advise you to go for the the second one, if you have to the same set of functionalities for both the buttons. 如果两个按钮都必须具有相同的功能,我建议您进行第二个尝试。

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

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