触发C#Button的双击事件

在C#中,Button是有DoubleClick事件的,只是它没有出现在事件列表中,而且.net也是把这个事件给"屏蔽"掉了,无论你双击一个按钮怎么快,也不会触发这个事件。

为了能够触发Button的双击事件,我们可以重载MouseDown事件,记录每次鼠标按下的时间,如果两次点击的时间足够近的话,就触发一次双击方法。

这样也大致能够达到双击的效果,我所采用的方法其实和这个类似,是继承Button类,重载Button类的Click事件,在Click事件中判断两次点击的时间,如果近的话,就触发双击事件。废话少说,上代码:


//======================================================================
//
//        Copyright (C) 2007-2008 杭州石鼓文信息科技有限公司    
//        All rights reserved
//
//        filename :ButtonEx
//        description :
//
//        created by 叶进 at  10/13/2008 15:38:24
//        http://adaiye.cnblogs.com
//
//======================================================================

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;


    
public class ButtonEx : Button
    {
        
public new event EventHandler DoubleClick;

        DateTime clickTime;
        
bool isClicked = false;

        
protected override void OnClick(EventArgs e)
        {
            
base.OnClick(e);

            
if (isClicked)
            {
                TimeSpan span 
= DateTime.Now - clickTime;
                
if (span.Milliseconds < SystemInformation.DoubleClickTime)
                {
                    DoubleClick(
this, e);
                    isClicked 
= false;
                }
            }
            
else
            {
                isClicked 
= true;
                clickTime 
= DateTime.Now;
            }
        }
    }

这样,就可以为创建的ButtonEx按钮添加DoubleClick事件了:

button.DoubleClick += new EventHandler(Button_DoubleClick);  // 双击按钮事件

posted @ 2008-10-13 16:16  随风逝去(叶进)  阅读(11142)  评论(13编辑  收藏  举报
Free Web Counter
Free Web Counter