Reputation:
This is probably a very simple question, but for some reason, even the right way to web search for the answer eludes me...
I'm trying to create a user control that consists of a few labels and progress bars. However, I want the entire control to have a "Click" event that is raised no matter what item inside the control is clicked on. I've created a "HandleClick" procedure that is assigned to each control:
private void HandleClick(object sender, EventArgs e)
{
// Call the callback function, if we were asked to
if (OnClick != null)
{
EventArgs ee = new EventArgs();
OnClick(this, ee);
}
else
{
MessageBox.Show("OnClick was null!");
}
}
OnClick in this instance is a variable defined at control level:
public new event EventHandler OnClick;
Now, this only works properly on the form. On one label it shows the MessageBox, and then calls the event on the enclosing form. All the rest show the message box.
I get the feeling that this should be obvious, but an afternoon of frustration has left me feeling I'm missing something that should be self-evident, but when I see it I am going to feel like a complete buffoon... can anyone stop giggling at my daftness long enough to enlighten me where I've gone wrong?
Upvotes: 5
Views: 8080
Reputation:
Sorry about this - just putting an answer on in case someone googles it...
In case you're interested, this post helped solve it: User Control Click - Windows Forms… Basically, remove HandleClick, and the property and substitute this one instead:
public new event EventHandler Click
{
add
{
base.Click += value;
foreach (Control control in Controls)
{
control.Click += value;
}
}
remove
{
base.Click -= value;
foreach (Control control in Controls)
{
control.Click -= value;
}
}
}
Upvotes: 10
Reputation: 133950
I've never tried this with Windows Forms, but in other GUIs I've placed a transparent panel that covers the entire form so that when you click "on the form," the event actually goes to the panel control.
Upvotes: -1