有没有办法创建一个共同的事件?

时间:2015-06-11 21:15:16

标签: c# winforms

我正在创建一种日志记录机制。任务是记录每个按钮单击并检查生产环境中最常用的功能。

我想知道是否有办法为我的应用程序中的所有按钮点击创建一个事件,包括引用的项目。因此,当单击按钮时,在按钮的单击事件处理程序之后运行中央代码。

3 个答案:

答案 0 :(得分:3)

不幸的是,没有简单的方法可以自动将代码挂钩到应用程序中每个按钮中的每个Click事件。

但是,您可以捕获Windows消息,检查来自任何按钮的点击消息。

所以你可以用IMessageFilter这种方式来做一些关于点击了哪个按钮的统计数据。

public partial class Form1 : Form, IMessageFilter
{
    public Form1()
    {
        InitializeComponent();
        Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == 0x0201) // This is left click
        {
            var ctrl = Control.FromHandle(m.HWnd);
            if (ctrl is Button)
                Debug.WriteLine(ctrl.Name);
        }
        return false;

    }
}

答案 1 :(得分:3)

你可以像这样做一个系统范围的过滤器:

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

namespace WindowsFormsApplication2
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.AddMessageFilter(new MyMessageFilter());  // hook filter up here

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

    // ---- Customer Message Filter ---------

    class MyMessageFilter : IMessageFilter
    {
        public bool PreFilterMessage(ref System.Windows.Forms.Message Msg)
        {
            const int WM_LBUTTONDOWN = 0x0201;

            if (Msg.Msg == WM_LBUTTONDOWN)
            {
                Control ClickedControl = System.Windows.Forms.Control.FromChildHandle(Msg.HWnd);


                if (ClickedControl != null)
                {
                    Button ClickedButton = ClickedControl as Button;

                    if (ClickedButton != null)
                    {
                        System.Diagnostics.Debug.WriteLine("CLICK =  Form: " + ClickedButton.Parent.Text + "  Control: " + ClickedButton.Text);
                    }
                }
            }
            return false;
        }
    }
}

答案 2 :(得分:2)

  

我想知道是否有办法为我的应用程序中的所有按钮点击创建一个事件

没有。所有其他解决方案只是解决方法,并且都有自己的问题。

您可以创建一个基本表单,并使用它而不是您正在使用的常规Form类。在OnHandleCreated中,您可以遍历所有控件,过滤掉按钮并注册click事件处理程序。 (注意在将所有已注册的对象保留在内存中时可能导致内存问题的引用)

另一个选项是将所有按钮控件替换为覆盖OnClick方法的Button类的自己派生版本。

相关问题