views:

60

answers:

2

Hello,

In my case I have panels,but to make it clear I will use buttons in my example.

I have 5(or more) buttons and I set an event,for example - OnMouseHover, to all of the five buttons.How do I get ,which one has the mouse hovered if all the events link to one method

To capture the button where the mouse is hovered,I tried using "this",but it links to the form itself.

    private void buttonX_MouseHover(object sender, EventArgs e)
    {
        this.Text = "Test";
    }

I expected the text on the specified button where the mouse is hovered to change its text to "Test",but it happened on the form.Text only.

In my real program,I have 60 panels and I again use one method for all OnMouseHover events on any of them.How do I get the panel(or button in the example above) where the mouse is hovered?

+8  A: 

this always refers to the class instance (the form). You need to cast the sender instead:

((Control)sender).Text = "Test";

The sender is (generally) the instance raising the event - useful when using the same handler from multiple controls.

Marc Gravell
Thanks,you saved my day! I have only one question.Is the "sender" in all events linked to the control?
John
@John: yes, it's always linked to whatever instance raises the event – in the case of controls, that's the current control.
Konrad Rudolph
However, when raising events yourself you need to make sure to pass the appropriate instance (`this`) manually, since this isn't ensured by the compiler. I guess that's what Marc means by “generally” in his answer.
Konrad Rudolph
Exactly. This is also the case if you do event shimming: "public event EventHandler SomeEvent {add {innerControl.SomeEvent += value;} remove {innerControl.SomeEvent -= value;}} - here, the sender is the innerControl, not the outer control... to get it right you would need to handle and re-raise the event with a different sender.
Marc Gravell
+2  A: 

This always is the class, in this case the form itself. The object "sender" is the magic word. If it is a button cast it back into a button. Since the object is only a reference you can make changes to the sending object.

Holli