Trương Phúc Anh Trương Phúc Anh - 15 days ago 6
C# Question

c# buttons image control with mouse event

I have 3 button in my form, and i'm finding a way to control its images when a mouse event happens


  • when i click button 1: set button 2 and 3 image with normal images, set button 1 with "mouse click" image.

  • when i click button 2: set button 1 and 3 image with normal images, set button 2 with "mouse click" image.
    ...



That's what i'm trying to do

And I want something sorter and can be use for more buttons, Like default button events or like (just 1 function for all buttons):
button A is sender -> reset all and set button A

Answer

You Can create one event for all the function and could be used like

private void ButtonAll_Click(object sender, MouseEventArgs e)
{
    ResetAllButtonImage();
    Button b = sender as Button;
    if(b.Text == "A") // or tag or Name Something to find
    {
        b.Image=(Image)(Properties.Resources.MouseClickThietLap);
    }
    else if(b.Text == "B")
    {
        b.Image=(Image)(Properties.Resources.MouseClickKhachHang);
    }
    else
    {
        b.Image=(Image)(Properties.Resources.MouseClickDoanhSo);
    }
}

And all the buttons should be pointing to this Event. You can do it from the Form Design Properties or Form.Designer.cs

this.Button1.Click += new System.EventHandler(this.ButtonAll_Click);
this.Button2.Click += new System.EventHandler(this.ButtonAll_Click);
this.Button3.Click += new System.EventHandler(this.ButtonAll_Click);