我有一个 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/