Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triple Mouse Click in C#?

In MS-Word Mouse Click events are used as:

Single Click - placing Cursor
Double Click - Selects Word
Triple Click - Selects Paragraph

In C# I can handle single and double mouse click events but I want to handle a Triple Mouse Click event in C# Windows TextBox.

Example:

void textbox1_TripleClick()
{
    MessageBox.Show("Triple Clicked"); 
} 
like image 810
Javed Akram Avatar asked Feb 16 '11 09:02

Javed Akram


2 Answers

Have a look at this: Mousebuttoneventargs.clickcount

That should cover it I suppose.

like image 123
Abuh Avatar answered Oct 16 '22 13:10

Abuh


I have adapted Jimmy T's answer to encapsulate the code into a class and to make it easier to apply to multiple controls on a form.

The class is this:

    using System.Windows.Forms;

    public class TripleClickHandler
    {
        private int _clicks = 0;
        private readonly System.Windows.Forms.Timer _timer = new System.Windows.Forms.Timer();
        private readonly TextBox _textBox;
        private readonly ToolStripTextBox _toolStripTextBox;

        public TripleClickHandler(TextBox control)
        {
            _textBox = control;
            _textBox.MouseUp += TextBox_MouseUp;
        }
        public TripleClickHandler(ToolStripTextBox control)
        {
            _toolStripTextBox = control;
            _toolStripTextBox.MouseUp += TextBox_MouseUp;
        }
        private void TextBox_MouseUp(object sender, MouseEventArgs e)
        {
            _timer.Stop();
            _clicks++;
            if (_clicks == 3)
            {
                // this means the trip click happened - do something
                if(_textBox!=null)
                    _textBox.SelectAll();
                else if (_toolStripTextBox != null)
                    _toolStripTextBox.SelectAll();
                _clicks = 0;
            }
            if (_clicks < 3)
            {
                _timer.Interval = 500;
                _timer.Start();
                _timer.Tick += (s, t) =>
                {
                    _timer.Stop();
                    _clicks = 0;
                };
            }
        }
    }

Then, to apply it to a textbox you can do this:

partial class MyForm : Form
{
    UIHelper.TripleClickHandler handler;
    public MyForm()
    {
        InitializeComponent();
        handler = new UIHelper.TripleClickHandler(myTextBox);
    }
}

Or, if you aren't otherwise using the control's tag you can simply do this:

partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();
        myTextBox.Tag = new UIHelper.TripleClickHandler(myTextBox);
    }
}
like image 40
Adrian Bhagat Avatar answered Oct 16 '22 12:10

Adrian Bhagat