Reputation: 2108
I had created a simple C# program with Mainform.cs, Mainform.Designer.cs and Program.cs files with SharpDevelop.
In that, i added a label at Point(10,10) in the form like this:
l.Text="Welcome";
l.Location=new System.Drawing.Point(10,10);
l.Size=new System.Drawing.Size(100,100);
mainForm.Controls.Add(l);
And then added an event handler for identifying mouse clicking on the form. When clicking a label to change its text.
l.Text="Clicked";
But it only changes text when clicking point less than (10,10). How to make it to change text when clicking anywhere on the window?
Thanks!
Upvotes: 0
Views: 101
Reputation: 63387
Of course attaching the same handler
for both the Click
event of your Form
and your Label
is OK, however what if you add more containers with nested relationship? I would go for a global Click event
solution by using an IMessageFilter
, something like this:
public partial class Form1 : Form, IMessageFilter {
public Form1(){
InitializeComponent();
Application.AddMessageFilter(this);
//Try this to see it in action
GlobalClick += (s,e) => {
l.Text = "Clicked";
};
}
public event EventHandler GlobalClick;
public bool PreFilterMessage(ref Message m){
if(m.Msg == 0x202){//WM_LBUTTONUP
EventHandler handler = GlobalClick;
if(handler != null) handler(this, EventArgs.Empty);
}
return false;
}
}
Upvotes: 2
Reputation: 35921
Attach the same event handler also to label's Clicked event, not only the form's event. In the version you've described the click events are being consumed by the Label
control, and not being passed to the form.
Upvotes: 2