如果给一个控件同时添加了单击事件和双击事件,那么在触发双击事件前必然会触发单击事件,为了解决这个问题,在网上一顿找,在msdn上找到了微软提供的解决方法:http://msdn.microsoft.com/en-us/library/ms171543(VS.80).aspx。英文好的同学可以不往下看了,:-D。
其主要思想是:单击鼠标时,启动一个Timer,Timer起计时器作用,Timer运行时间超过了一次双击鼠标所用的最长时间,而第二次鼠标点击事件还没有发生时,就认为是单击,反之,如果在一个鼠标双击所用时间的最长时间内,又一次触发了鼠标点击事件,则可视为双击。
以下是实例代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace DoubleClick { public partial class Form1 : Form { private bool _isFirstClick = true; private bool _isDoubleClick = false; private int _milliseconds = 0; private Timer _doubleClickTimer; private Rectangle _doubleRec; public Form1() { InitializeComponent(); this.button1.MouseDown += new MouseEventHandler(button1_MouseDown); _doubleClickTimer = new Timer(); _doubleClickTimer.Interval = 100; _doubleClickTimer.Tick += new EventHandler(_doubleClickTimer_Tick); } //_doubleClickTimer的Tick事件 private void _doubleClickTimer_Tick(object sender, EventArgs e) { _milliseconds += 100; if (_milliseconds >= SystemInformation.DoubleClickTime) { _doubleClickTimer.Stop(); if (_isDoubleClick) { MessageBox.Show("Double Click"); } else { MessageBox.Show("Single Click"); } _isDoubleClick = false; _isFirstClick = true; _milliseconds = 0; } } //鼠标按下事件 private void button1_MouseDown(object sender, MouseEventArgs e) { if (_isFirstClick) { _doubleRec = new Rectangle(e.X - SystemInformation.DoubleClickSize.Width / 2, e.Y - SystemInformation.DoubleClickSize.Height / 2, SystemInformation.DoubleClickSize.Width, SystemInformation.DoubleClickSize.Height); _isFirstClick = false; _doubleClickTimer.Start(); } else { if (_doubleRec.Contains(e.Location)) { _isDoubleClick = true; } } } } }