Search code examples
c#mousedown

Having minimum mousedown time on control


I have a control (basically an ON/OFF toggle switch) which I want the user to press for at least one second before switching states. I can measure the time between the mouse down and mouse up events on the control and make sure the mouse never leaves the control while down, but wanted to know:

Is there was a better method of establishing that the "click" on that control satisfies a minimum time?


Solution

  • There is no simpler way, you must do the steps you have described.

    But, this "behavior" can be implemented in a general way - so it can be reused multiple times.

    Here is an example of such implementation:

    public class LongClick
    {
        public static void Attach(Control Control, EventHandler Handler)
        {
            var LC = new LongClick { Control = Control, Handler = Handler };
            Control.MouseDown += LC.ControlOnMouseDown;
            Control.MouseMove += LC.ControlOnMouseMove;
            Control.MouseUp += LC.ControlOnMouseUp;
        }
    
        private Control Control;
        public EventHandler Handler;
        private DateTime? MDS;
    
        private void ControlOnMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) MDS = DateTime.Now;
        }
        private void ControlOnMouseMove(object sender, MouseEventArgs e)
        {
            if (MDS == null) return;
            if (e.X < 0) MDS = null;
            if (e.X > Control.Width) MDS = null;
            if (e.Y < 0) MDS = null;
            if (e.Y > Control.Height) MDS = null;
        }
        private void ControlOnMouseUp(object sender, MouseEventArgs e)
        {
            if (MDS == null) return;
            if (e.Button != MouseButtons.Left) return;
            var TimePassed = DateTime.Now.Subtract(MDS.Value);
            MDS = null;
            if (TimePassed.TotalSeconds < 1) return;
            if (Handler == null) return;
            Handler(Control, EventArgs.Empty);
        }
    }
    

    And the usage is:

    private void Form1_Load(object sender, EventArgs e)
    {
        LongClick.Attach(button1, button1_LongClick);
    }
    
    private void button1_LongClick(object sender, EventArgs e)
    {
        MessageBox.Show("button1 long clicked!");
    }
    

    There are other variations of the implementation, one of them would be to override the control class (it is even simpler than this one).