鼠标点击计数器! [英] Mouse Click Counter!

查看:256
本文介绍了鼠标点击计数器!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何计算鼠标单击的次数?

How can we count how many times a mouse click hsa been made?

推荐答案

我更喜欢通过IMessageFilter界面和Application.AddMessageFilter进行此操作.请参考此示例实现:

I''d prefer doing this via IMessageFilter interface and Application.AddMessageFilter. Please refer to this sample implementation:

public class MessageFilter : IMessageFilter
{
    long countMouse;
    Form1 form;
    public MessageFilter(Form1 form)
    {
        countMouse = 0;
        this.form = form;
    }
    private const int WM_LBUTTONDOWN = 0x201;
    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == WM_LBUTTONDOWN)
        {
            countMouse++;
            form.label1.Text = String.Format("Clicks: {0}", countMouse);
        }
        return false;
    }
}



在设置应用程序的程序代码中执行以下操作:



in the Program code where the Application is setup do this:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Form1 form = new Form1();
        Application.AddMessageFilter(new MessageFilter(form));
        Application.Run(form);
    }
}



请注意,这仅是 出于演示目的.在这个简单的示例中,我永远不会公开Label,但是对于一个简单的演示来说,它就足够了.即使单击深度嵌套的控件,该过滤器也会被调用.消息过滤器还应该不知道具体的表单实现.这样做也仅出于演示目的.

祝您编程愉快,万事如意!

-MRB



Please take note that this is only for demonstration purposes. I''d never make a Label public as it needs to be in this simple example, but it''s enough for a simple demonstration. The filter will be called even when you click on however deeply nested controls. The message filter should also be unaware of the concrete form implementation. This was also done only for demonstration purposes.

Happy programming and cheers!

-MRB


您可以使用MouseDown事件:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousedown.aspx [ ^ ]

在事件内部添加一个静态计数器,或者在窗体级别添加一个私有计数器,然后在mousedown中增加计数器.
You can use the MouseDown event:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousedown.aspx[^]

Add a static counter inside the event or a private on form level and increase the counter in mousedown.


这篇关于鼠标点击计数器!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆