I want to catch the event that user clicks and holds mouse on a control in C#.
I have read on MSDN and I only see events Mouse Down, Mouse Up, ... but don't have Move Hold event.
I want to catch the event that user clicks and holds mouse on a control in C#.
I have read on MSDN and I only see events Mouse Down, Mouse Up, ... but don't have Move Hold event.
You need to use mentinoed events with some timer between them.
Example:
In case if user holds more then timer time - invoke your event handler, when mouseUp happend faster then timer elapsed - disable runned timer.
public bool down;
private void ControlName_MouseDown(object sender, MouseEventArgs e)
{
down = true;
}
private void ControlName_EventName(object sender, EventArgs e)
{
if (down) {// code if the mouse is held
}
}
private void ControlName_MouseUp(object sender, MouseEventArgs e)
{
down = false;
}
The accepted answer and comments are already good but the following simple implementation may be useful for posterity:
using System;
using System.Windows.Forms;
namespace WinFormsTest
{
public partial class Form1 : Form
{
private readonly Timer timer;
public Form1()
{
InitializeComponent();
timer = new Timer();
timer.Interval = 3000;
timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
timer.Enabled = false;
MessageBox.Show("MouseHold");
}
private void Button_MouseDown(object sender, MouseEventArgs e)
{
timer.Start();
}
private void Button_MouseUp(object sender, MouseEventArgs e)
{
timer.Enabled = false;
}
}
}
Please note that:
MouseUp
event outside the Button
then this will be ignored and the handler method will work anyway.First, you should use stop watch to detect time you want.
using System.Diagnostics;
Second, define a global instance of stopwatch class.
Stopwatch s = new Stopwatch();
This is the first event you should use:
private void controlName_MouseDown(object sender, MouseEventArgs e)
{
s.Start();
}
This is the second event you should use:
private void controlName_MouseUp(object sender, MouseEventArgs e)
{
s.Stop();
//determine time you want . but take attention it's in millisecond
if (s.ElapsedMilliseconds <= 700 && s.ElapsedMilliseconds >= 200)
{
//you code here.
}
s.Reset();
}