Windows Develop Bookmark and Share   
 index > Windows Forms General > Handle forms click event when any control clicked on top of the form
 

Handle forms click event when any control clicked on top of the form

Hello,

I would like to create an event handler that is raised when any control is clicked on a form. However I don't want to have to hook up the event handler for each control on the form as this would be hard to maintain. It seems that if a control is placed on top of the form the forms on click event is blocked and only the controls on click event is raised.

So I would be most greatful if anyone knows if there is a way I can make the forms click event fire when I click on any other control on the form?

Thanks,

Caroline
Caroline81  Thursday, October 01, 2009 12:11 PM
It is quite unusual to have this requirement. It is however easy to implement. For example:

public partial class Form1 : Form {
public Form1() {
InitializeComponent();
wireClick(this.Controls);
}
private void wireClick(Control.ControlCollection ctls) {
foreach (Control ctl in ctls) {
ctl.Click += anyControl_Click;
wireClick(ctl.Controls);
}
}
private void anyControl_Click(object sender, EventArgs e) {
Control ctl = sender as Control;
if (ctl != null) {
// etc...
}
}
}


Hans Passant.
  • Proposed As Answer byScottyDoesKnow Thursday, October 01, 2009 2:04 PM
  • Marked As Answer byCaroline81 Thursday, October 01, 2009 2:08 PM
  •  
nobugz  Thursday, October 01, 2009 12:41 PM
It is quite unusual to have this requirement. It is however easy to implement. For example:

public partial class Form1 : Form {
public Form1() {
InitializeComponent();
wireClick(this.Controls);
}
private void wireClick(Control.ControlCollection ctls) {
foreach (Control ctl in ctls) {
ctl.Click += anyControl_Click;
wireClick(ctl.Controls);
}
}
private void anyControl_Click(object sender, EventArgs e) {
Control ctl = sender as Control;
if (ctl != null) {
// etc...
}
}
}


Hans Passant.
  • Proposed As Answer byScottyDoesKnow Thursday, October 01, 2009 2:04 PM
  • Marked As Answer byCaroline81 Thursday, October 01, 2009 2:08 PM
  •  
nobugz  Thursday, October 01, 2009 12:41 PM
Thanks,

That worked well, I just wish I thought of it.

Thanks again,

Caroline
Caroline81  Thursday, October 01, 2009 2:08 PM

You can use google to search for other answers

Custom Search

More Threads

• Giving a code generated panel a handler
• Embed a Java applet in a C# windows form.
• Unable to get the window handle for the 'xxx control. Windowless ActiveX controls are not supported.
• http post request
• Named Pipes
• Translate this code from C# to VB.Net
• richTextBox, simple visual problem.
• MonthCalendar Control: DateSelected fires when the Calendar Header is clicked
• Decompile .NET
• C# Disable certain key combonations?