[添加WinForms应用程序中的所有日志单击按钮

问题描述 投票:1回答:2

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

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); } }
此类在构造函数的末尾以某种形式使用,例如:

ButtonLogger.AttachButtonLogging(this.Controls);

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

是否有一种方法可以利用表单上的所有按钮,而不管它们的父容器是什么?我的最终目标是在按钮上添加一条日志语句,因此,如果可以通过按钮单击事件方法之外的其他方式来完成此操作,那么我也可以这样做

c# winforms button logging
2个回答
4
投票
我相信您需要递归搜索按钮:

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); } } }


0
投票
您可以考虑的一件事是创建标准Button类的子类,然后让按钮自己进行日志记录。当然,您必须四处走动,并用应用程序中的所有按钮替换自己的实现,但是应该可以通过全局搜索+替换来做到这一点。

这是示例实现:

public class LoggerButton : Button { private static readonly ILog Logger = LogManager.GetLogger(typeof(LoggerButton)); protected override void OnClick(EventArgs e) { base.OnClick(e); Logger.InfoFormat("Button clicked: {0} ({1})", this.Text, this.Parent.Text); } }

© www.soinside.com 2019 - 2024. All rights reserved.