【问题标题】:C# Event Handler is called multiple times when selecting a menu item选择菜单项时多次调用 C# 事件处理程序
【发布时间】:2020-05-15 10:30:42
【问题描述】:

我想实现一些图片框,当其中一个被点击时,应该会出现一个消息框并告诉你点击了哪个框。

但是,我想选择应该出现多少个图片框。当我选择另一个 MenuItem 时,单击事件将被多次调用。我试过退订,但没用。

这是我的代码:

public partial class Form1 : Form
{
    PictureBox Pbox1;
    PictureBox Pbox2;
    PictureBox Pbox3;
    PictureBox Pbox4;

    public Form1()
    {
        InitializeComponent();
        this.Text = "Picturebox";

        Pbox1 = new PictureBox();
        Pbox2 = new PictureBox();
        Pbox3 = new PictureBox();
        Pbox4 = new PictureBox();
    }

    private void Pbox_Click(object sender, EventArgs e, int nr)
    {
        MessageBox.Show("Picture number " + nr.ToString() + " is clicked");
    }

    private void toolStripMenuItem2_Click(object sender, EventArgs e)
    {
        Pbox1.Image = new Bitmap(@"Picture.png");
        Pbox1.Location = new Point(20, 40);
        Pbox1.Size = new Size(160, 120);
        Pbox1.SizeMode = PictureBoxSizeMode.StretchImage;

        Pbox1.Click += (sender2, e2) => Pbox_Click(sender2, e2, 1);
        this.Controls.Add(Pbox1); }

其余与toolStripMenuItem2相同。

你能帮我解决这个问题吗?

【问题讨论】:

标签: c# eventhandler


【解决方案1】:

什么时候会被多次调用?我想当切换到另一个菜单项时,一切都应该正常。但是当切换回之前已经点击过的项目时,除了现有的点击处理程序之外,还会注册另一个点击处理程序,并会调用 Pbox_Click 方法两次。

您可以尝试将事件注册放在构造方法中,或者在重新注册之前释放其他点击事件。

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多