Monday, November 19, 2007

How to set up MouseClick and MouseDoubleClick in 6 steps (C# / Visual Studio 2005)

Do you want to add clicking and double clicking to the same button in C#? This is the only way I have found that works:

  1. Start by adding an integer variable to set the status for the mouse and initialize to zero (clickStatus)
  2. Drag a timer to the form to monitor how much time have elapsed between mouse clicks (timer1). Set “Enabled” property to “false”.
  3. Set the timer interval to the system doubleclick time (timer1.Interval=SystemInformation.DoubleClickTime)
  4. Add a Click event to the form or whatever you want to check the clickstatus of.
  5. Add the Click event to the Tick event of timer1
  6. Add additional code as shown below:

    namespace WindowsApplication3
    {
    public partial class Form1 : Form
    {
    private int clickStatus=0; //0=not clicked, 1=single clicked, 2=double clicked

    public Form1()
    {
    InitializeComponent();
    timer1.Interval = SystemInformation.DoubleClickTime;
    }
    private void Form1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
    clickStatus = 2;
    }
    private void Form1_MouseClick(object sender, MouseEventArgs e)
    {
    clickStatus = 1;
    timer1.Enabled = true;
    }
    private void Form1_Click(object sender, EventArgs e)
    {
    timer1.Enabled = false;
    if (clickStatus==2)
    {
    //MessageBox.Show("Double clicked");
    clickStatus = 0;
    }
    else if (clickStatus==1)
    {
    //MessageBox.Show("Single clicked");
    clickStatus = 0;
    }
    }
    }
    }

    The click events are called in the following order: Click – MouseClick – MouseDoubleClick, but MouseDoubleClick will not be raised if a MouseClick is raised. The trick is to use the timer. When a single click is made then the following events will be raised: Click – MouseClick – Click. When a double click Is made the following events will be raised: Click – MouseClick – MouseDoubleClick – Click. Make sure to add the same events to other components that you want to have similar behaviour (labels, boxes etc).