单击任何按钮的事件(C# windows 窗体) [英] Event for Click in any button (C# windows forms)

查看:30
本文介绍了单击任何按钮的事件(C# windows 窗体)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个程序,该程序有许多按钮,单击时应该执行类似的操作,但根据单击的按钮略有不同.问题是唯一直接的方法是为每个按钮编码,这将是一项非常重复的任务.有没有一种方法可以简单地对一个块进行编程,该块可以点击任何按钮并点击哪个按钮?

I'm developing a program that has many buttons that should do a similar action when clicked, but with a small difference based on which button was clicked. The problem is that the only straightforward path is to code this for each button, which would be a very repetitive task. Is there a way to program simply one block that would get the click on any button and which button was clicked?

推荐答案

为所有按钮分配相同的事件处理程序.

Assign the same event handler to all buttons.

foreach (var button in Controls.OfType<Button>()) {
    button.Click += button_Click;
}

或者您可以在切换到事件的属性窗口中选择相同的事件处理程序(闪烁图标).

Or you can select the same event handler in the properties window switched to events (flash icon).

private static void button_Click(object sender, EventArgs eventArgs)
{
    switch (((Button)sender).Name)
    {
        // find a way to disambiguate.
    }
}

您还可以向 Tag 属性添加一些有用的信息以消除歧义.最后但并非最不重要的一点是,您可以从 Button 派生出自己的按钮并添加适当的属性.它们甚至会出现在属性窗口中.

You can also add some useful information to the Tag property for the disambiguation. And last but not least, you can derive your own button from Button and add appropriate properties. They will even appear in the properties window.

这篇关于单击任何按钮的事件(C# windows 窗体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆