Thursday, January 3, 2013
How to make Single Click and Double Click Events work together in windows form?
While working with Windows Application, This is common problem that- Single Click and Double Click Events don't work together (If you have any processing code in Single Click Event like- Showing message using MessageBox), means if we have written some code in Single Click Event and some lines of code in Double Click Event then always Single Click Event code will be executed.
I also faced same problem and came with one workaround.
See this example-
private void Form1_Click(object sender, EventArgs e)
{
MessageBox.Show("Single Click Event");
}
private void Form1_DoubleClick(object sender, EventArgs e)
{
MessageBox.Show("Double Click Event");
}
In above lines of code always Single Click Event code will be executed and always output will be - Single Click only.
In this article, I am explaining - How to make Single Click and Double Click Events work together?
Workaround-
To resolve this problem, I have taken one Timer Control, using Timer control I am handling the Single and Double Click Events functionalities.
Here is the code-
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = SystemInformation.DoubleClickTime;
}
private void Form1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void Form1_DoubleClick(object sender, EventArgs e)
{
timer1.Enabled = false;
MessageBox.Show("Double Click Event");
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
MessageBox.Show("Single Click Event");
}
In above code, first I am setting Timer Interval as System Double Click Time value. This can be different based on Operating System Settings.
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = SystemInformation.DoubleClickTime;
}
Now in Single Click Event, I am just enabling the Timer to execute the code which is written in Tick() Event of Timer.
private void Form1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
In Tick() event write the code which you want to execute in Single Click Event.
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
MessageBox.Show("Single Click Event");
}
Here I am disabling the Timer Control also because this code will be executed once.
Now this is Double Click Event code-
private void Form1_DoubleClick(object sender, EventArgs e)
{
timer1.Enabled = false;
MessageBox.Show("Double Click Event");
}
Here I am just disabling the Timer Control; here you need to put actual Double Click Event code.
Here all the functionalities depend on Timer Control, Here making Timer control enable and disable is making trick for us.
Try this code.
Thanks
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment