简体   繁体   English

为什么在此代码中多次运行MessageBox?

[英]Why does MessageBox be run several times in this code?

I'm a newbie in programming and writing codes. 我是编程和编写代码的新手。 I have a very simple form with 6 buttons. 我有一个非常简单的表格,带有6个按钮。 When I click on every button only the sender's text got Magenta. 当我单击每个按钮时,仅发件人的文本变为洋红色。 But Button3 do a further work and that's opening a "Hello" messageBox. 但是Button3要做进一步的工作,并且正在打开“ Hello”消息框。 The problem is when I click on Button3, it shows "hello" string 4 times. 问题是当我单击Button3时,它显示“ hello”字符串4次。 Why? 为什么? I think and expect it show it just once no more. 我认为并且期望它不会再显示一次。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Typhok(object sender, EventArgs e)
    {
        foreach (Control x in this.Controls)
        {
            if (x.Equals(sender))
                x.ForeColor = Color.Magenta;
            else
                x.ForeColor = Color.Black;
        }
        b3.Click += new EventHandler(Popup);
    }

    private void Popup(object sender, EventArgs e)
    {
        MessageBox.Show("hello!");
    }
}

UPDATE: Can anyone explain to me why that original code had that problem? 更新:谁能向我解释为什么原始代码有这个问题?

Register event handler in constructor, not in Typhok method. 在构造函数中而不是Typhok方法中注册事件处理程序。 The final code should look like: 最终代码应如下所示:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        b3.Click += new EventHandler(Popup);
    }

    private void Typhok(object sender, EventArgs e)
    {
        foreach (Control x in this.Controls)
        {
            if (x.Equals(sender))
                x.ForeColor = Color.Magenta;
            else
                x.ForeColor = Color.Black;
        }
    }

    private void Popup(object sender, EventArgs e)
    {
       MessageBox.Show("hello!");
    }
}

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

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