簡體   English   中英

更改鼠標 hover 上的按鈕顏色

[英]Change button color on mouse hover

在C#中,如何改變鼠標指針在按鈕上時的顏色,使鼠標離開時按鈕的顏色恢復到之前的顏色。

假設您使用的是 Windows.Forms,您可以將事件處理程序添加到ButtonMouseEnterMouseLeave事件,並相應地設置ButtonBackColor屬性:

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;
  }
}

下面的代碼對我有用。

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.**
}

您並不是很具體,但如果您願意,可以使用 MonoGame 庫。 如果您確實選擇使用它(通常不推薦用於計算器等簡單程序,但它仍然可以完成工作),您應該執行以下操作:

//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();

然而,正如另一個答案所說,最好使用 Windows 窗體,因為它更適合這樣一個簡單的程序,並且不需要非常精美或靈活的圖形界面。

無需懸停/離開事件或繪圖。

只需使您的按鈕變平並使用MouseOverBackColor屬性。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM