我有一个ac#form(让我们称之为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); } } } }
此解决方案不仅适用于顶级控件,还适用于嵌套控件,例如放置在面板内的控件.