Search code examples
c#winformsopenfiledialogtoolstripbutton

Strange ToolStripButton click to open an OpenFileDialog behavior


I found a strange ToolStripButton double click problem. These steps will reproduce the problem:

  1. Create a Windows Form Application.
  2. Add a ToolStrip on the main form.
  3. Add a ToolStripButton on the ToolStrip.
  4. Add an OpenFileDialog on the main form.
  5. Double click the ToolStripButton's Click event on the property toolbox.
  6. Add this in toolStripButton1_Click method:

    openFileDialog1.ShowDialog();
    
  7. Start debug.
  8. Quickly double click the ToolStripButton.

Here comes the problem. First, an open file dialog pops up, and I close it, then another dialog pops up. This shouldn't happen. I close it again, then the main form may have some redraw problem. Finally, I close the main form, but the program is still running.

Please try it yourself and let me know if all those happens.

Why those happens? What should I do to solve it?

You can use this to reproduce the problem:

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace WinForm
{
    class MyForm : Form
    {
        private IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            openFileDialog1 = new OpenFileDialog();
            toolStrip1 = new ToolStrip();
            toolStripButton1 = new ToolStripButton();
            toolStrip1.SuspendLayout();
            this.SuspendLayout();
            toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripButton1 });
            toolStripButton1.Text = "toolStripButton1";
            toolStripButton1.Click += new EventHandler(toolStripButton1_Click);
            this.Controls.Add(toolStrip1);
            toolStrip1.ResumeLayout(false);
            toolStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private OpenFileDialog openFileDialog1;
        private ToolStrip toolStrip1;
        private ToolStripButton toolStripButton1;

        public MyForm()
        {
            InitializeComponent();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyForm());
        }
    }
}

Solution

  • I decided to use this (for now):

    private void toolStripButton1_Click(object sender, EventArgs e)
    {
        toolStripButton1.Enabled = false;
        openFileDialog1.ShowDialog();
        toolStripButton1.Enabled = true;
    }