c# - 如何为表单设置点击事件?

标签 c# winforms

我有一个 c# 窗体(我们称它为 MainForm),上面有许多自定义控件。我想让 MainForm.OnClick() 方法在有人单击表单时触发,无论单击是发生在表单上还是单击是在自定义控件之一上。我正在寻找类似于窗体的 KeyPreview 功能的行为,除了鼠标点击而不是按键。

最佳答案

我建议为应用程序中的其他表单创建一个基本表单以供继承。将此代码添加到您的基本表单以创建一个名为 GlobalMouseClickEventHandler 的新事件:

namespace Temp
{
    public delegate void GlobalMouseClickEventHander(object sender, MouseEventArgs e);

    public partial class TestForm : Form
    {
        [Category("Action")]
        [Description("Fires when any control on the form is clicked.")]
        public event GlobalMouseClickEventHander GlobalMouseClick;

        public TestForm()
        {
            InitializeComponent();
            BindControlMouseClicks(this);
        }

        private void BindControlMouseClicks(Control con)
        {
            con.MouseClick += delegate(object sender, MouseEventArgs e)
            {
                TriggerMouseClicked(sender, e);
            };
            // bind to controls already added
            foreach (Control i in con.Controls)
            {
                BindControlMouseClicks(i);
            }
            // bind to controls added in the future
            con.ControlAdded += delegate(object sender, ControlEventArgs e)
            {
                BindControlMouseClicks(e.Control);
            };            
        }

        private void TriggerMouseClicked(object sender, MouseEventArgs e)
        {
            if (GlobalMouseClick != null)
            {
                GlobalMouseClick(sender, e);
            }
        }
    }
}

此解决方案不仅适用于顶级控件,而且适用于嵌套控件,例如放置在面板内部的控件。

关于c# - 如何为表单设置点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/180452/

相关文章:

c# - 我无法在 C# 中正确运行带引号的 powershell 代码

c# - 如何引用 Route 和 ResponseType 属性?

c# - vsphere api 更改虚拟机的 IP 地址

c# - WinForms UI 有时无响应

c# - 单击 notifyIcon 时如何抑制 BalloonTipClicked 事件?

c# - PTP通讯

c# - C# 中的数组属性语法

c# - 如何将多个选定项目从一个列表框移动到另一个列表框?

c# - 文本框中的永久前缀

c# - 如何在 WPF 的图像控件中分配 System.Drawing.Image 对象