简体   繁体   中英

Change button color on mouse hover

In C #, how to change the color of the buttons when the mouse pointer is on them, so that the color of the button returns to the previous color when the mouse leaves it.

Supposing you are using Windows.Forms you can add event handlers to the MouseEnter and MouseLeave events of your Button and set the Button 's BackColor property accordingly:

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
    button1.MouseEnter += OnMouseEnterButton1;
    button1.MouseLeave += OnMouseLeaveButton1;
  }

  private void OnMouseEnterButton1(object sender, EventArgs e)
  {
    button1.BackColor = SystemColors.ButtonHighlight; // or Color.Red or whatever you want
  }
  private void OnMouseLeaveButton1(object sender, EventArgs e)
  {
    button1.BackColor = SystemColors.ButtonFace;
  }
}

below code worked for me.

private void shipdbutton_MouseHover(object sender, EventArgs e)
{
    shipdbutton.BackColor = Color.White;
}

private void shipdbutton_MouseLeave(object sender, EventArgs e)
{
    shipdbutton.BackColor = Color.FromArgb(32, 38, 71); // ****add the color you want here.**
}

You're not really being very specific, but you could use the MonoGame library if you wanted to. If you do choose to use it (generally not recommended for simple programs like a calculator, but it does the job nonetheless), you should do something like this:

//1. Declare your button's texture, and some other stuff (button rectangle, etc.).    
Texture2D My_texture;
Rectangle buttonBox;
bool isMouseIn = false;

//2. Load your button's texture in the LoadContent() method.
My_texture = Content.Load<Texture2D>("name of your resource");

//3. Handle the input in the Update() method.
MouseState currentMouseState = Mouse.GetState();
if(buttonBox.Contains(currentMouseState.Position))
{
    isMouseIn = true;
}


//4. Draw the button in the Draw() method.
spriteBatch.Begin();
if(isMousein)
{
    spriteBatch.Draw(My_texture, buttonBox, Color.Red;
}
else
{
    spriteBatch.Draw(My_texture, buttonBox, Color.Blue);
}
spriteBatch.End();

It is however better to use Windows Forms as the other answer says, since it is more suited to such a simple program and does not require a very polished or flexible graphical interface.

No need hover/leave events or drawing.

Just make your button flat and use MouseOverBackColor property.

Button.FlatStyle = FlatStyle.Flat;
Button.FlatAppearance.MouseOverBackColor = Color.Red; //color you want it to be background on hover

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM