记录WinForms应用程序中的所有按钮单击 [英] Logging all button clicks in WinForms app

查看:99
本文介绍了记录WinForms应用程序中的所有按钮单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望为用户单击的每个WinForms按钮单击添加一条日志语句,最好是为父窗体的标识符(例如标题栏)添加一个日志语句.我已经看到帖子记录了所有鼠标单击,但是我只对记录按钮单击感兴趣.我已经在此处中阅读并接受了该答案并对其进行了调整:

I'm looking to add a log statement for every WinForms button click that the user clicks, and ideally, an indentifier of the parent form (such as the title bar). I have seen posts logging all mouse clicks, but i'm interested in just logging button clicks. I have read the accepted answer here and adapted it:

public class ButtonLogger
{
    private static readonly ILog Logger = LogManager.GetLogger(typeof(ButtonLogger));
    public static void AttachButtonLogging(Control.ControlCollection controls)
    {
        foreach (var button in controls.OfType<Button>())
        {
            button.Click += LogButtonClick;
        }
    }
    private static void LogButtonClick(object sender, EventArgs eventArgs)
    {
        Button button = sender as Button;
        Logger.InfoFormat("Button clicked: {0} ({1})", button.Text, button.Parent.Text);
    }
}

此类在构造函数的末尾以某种形式使用,例如:

This class is used at the end of a constructor in a form, e.g. :

ButtonLogger.AttachButtonLogging(this.Controls);

我面临的问题是Controls属性似乎没有对我的按钮的引用.大概是因为这些按钮不是直接添加到窗体中,而是添加到Controls属性中的另一个控件.但是,Controls属性仅包含一个控件ToolStrip.

The problem I'm facing with this is that the Controls property doesn't seem to have a reference to my buttons. Presumably this is because the buttons aren't added directly to the form, but rather, another control that is in the Controls property. However, the Controls property only contains a single control, a ToolStrip.

有没有一种方法可以利用表单上的所有按钮,而不管它们的父容器是什么?我的最终目标是在按钮上添加一条日志语句,因此,如果可以通过按钮单击事件方法以外的其他方式来实现此目的,那么我也很乐意

Is there a way I can harness all of the buttons on a form, regardless of their parent container? My final goal is to add a log statement to my buttons, so if this can be accomplished some other way besides button click event methods, then I'm open to that as well

推荐答案

我相信您需要递归搜索按钮:

I believe you need to search for buttons recursively:

public static void AttachButtonLogging(Control.ControlCollection controls)
{
    foreach (var control in controls.Cast<Control>())
    {
        if (control is Button)
        {
           Button button = (Button)control;
           button.Click += LogButtonClick;
        }
        else
        {
            AttachButtonLogging(control.Controls);
        }
    }
}

这篇关于记录WinForms应用程序中的所有按钮单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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