记录所有按钮点击在Win窗体应用程序 [英] Log all button clicks in Win Forms app

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

问题描述

我期待添加日志语句的WinForms每按一下按钮,用户点击,和理想情况下,父窗体的indentifier(如标题栏)。我看到帖子登录全部鼠标点击,但我感兴趣的只是登录按钮点击。我已阅读接受的答案<一个href=\"http://stackoverflow.com/questions/12554314/event-for-click-in-any-button-c-windows-forms\">here并适应它:

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属性似乎没有要我的按钮的参考。 presumably这是因为按钮没有直接添加到形式,而是另一个控制即在控件属性。然而,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);
        }
    }
}

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

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