当选择一个菜单项时,C#事件处理程序被多次调用。

问题描述 投票:0回答:1

我想实现一些Pictureboxes,当其中一个Pictureboxes被点击时,就会出现一个MessageBox,并告知点击了哪个Picturebox。

然而,我想实现一个选择应该出现多少个Pictureboxes,当我选择另一个MenuItem时,那么点击事件将被多次调用。当我选择另一个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); }

其余的和工具条菜单项2一样。

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

c# eventhandler
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.