C# 处理窗体上所有控件的单击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/247946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling a Click for all controls on a Form
提问by ctacke
I have a .NET UserControl (FFX 3.5). This control contains several child Controls - a Panel, a couple Labels, a couple TextBoxes, and yet another custom Control. I want to handle a right click anywhere on the base Control - so a right click on any child control (or child of a child in the case of the Panel). I'd like to do it so that it's maintainable if someone makes changes to the Control without having to wire in handlers for new Controls for example.
我有一个 .NET UserControl (FFX 3.5)。该控件包含多个子控件 - 一个面板、一对标签、一对文本框和另一个自定义控件。我想在基本控件上的任何地方进行右键单击 - 因此右键单击任何子控件(或在面板的情况下是子控件的子控件)。我想这样做,以便在有人更改控件时它是可维护的,而不必为新控件连接处理程序。
First I tried overriding the WndProc, but as I suspected, I only get messages for clicks on the Form directly, not any of its children. As a semi-hack, I added the following after InitializeComponent:
首先,我尝试覆盖 WndProc,但正如我所怀疑的那样,我只收到直接点击表单的消息,而不是它的任何子节点。作为半黑客,我在 InitializeComponent 之后添加了以下内容:
foreach (Control c in this.Controls)
{
c.MouseClick += new MouseEventHandler(
delegate(object sender, MouseEventArgs e)
{
// handle the click here
});
}
This now gets clicks for controls that support the event, but Labels, for example, still don't get anything. Is there a simple way to do this that I'm overlooking?
这现在获得了支持该事件的控件的点击,但例如,标签仍然没有得到任何东西。有没有一种简单的方法可以做到这一点,我忽略了?
采纳答案by Mark Cidade
If the labels are in a subcontrol then you'd have to do this recursively:
如果标签在子控件中,那么您必须递归地执行此操作:
void initControlsRecursive(ControlCollection coll)
{
foreach (Control c in coll)
{
c.MouseClick += (sender, e) => {/* handle the click here */});
initControlsRecursive(c.Controls);
}
}
/* ... */
initControlsRecursive(Form.Controls);
回答by ChocapicSz
To handle a MouseClickevent for right click on all the controls on a custom UserControl:
要处理鼠标单击事件以右键单击自定义UserControl上的所有控件:
public class MyClass : UserControl
{
public MyClass()
{
InitializeComponent();
MouseClick += ControlOnMouseClick;
if (HasChildren)
AddOnMouseClickHandlerRecursive(Controls);
}
private void AddOnMouseClickHandlerRecursive(IEnumerable controls)
{
foreach (Control control in controls)
{
control.MouseClick += ControlOnMouseClick;
if (control.HasChildren)
AddOnMouseClickHandlerRecursive(control.Controls);
}
}
private void ControlOnMouseClick(object sender, MouseEventArgs args)
{
if (args.Button != MouseButtons.Right)
return;
var contextMenu = new ContextMenu(new[] { new MenuItem("Copy", OnCopyClick) });
contextMenu.Show((Control)sender, new Point(args.X, args.Y));
}
private void OnCopyClick(object sender, EventArgs eventArgs)
{
MessageBox.Show("Copy menu item was clicked.");
}
}