C# 鼠标悬停时更改按钮颜色

C# 鼠标悬停时更改按钮颜色,c#,C#,我正在用C写一个windows计算器。 我想当鼠标移到按钮上时,它会改变按钮的颜色,当鼠标移到其他位置时,按钮的颜色会恢复到原来的颜色。假设您使用的是Windows。窗体您可以将事件处理程序添加到鼠标指针和鼠标删除按钮的事件中,并设置按钮BackColor属性相应地: public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.MouseEnter += OnMou

我正在用C写一个windows计算器。
我想当鼠标移到按钮上时,它会改变按钮的颜色,当鼠标移到其他位置时,按钮的颜色会恢复到原来的颜色。

假设您使用的是Windows。窗体您可以将事件处理程序添加到
鼠标指针和
鼠标删除
按钮的事件中
,并设置
按钮
BackColor
属性相应地:

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

你不是很具体,但是如果你想的话,你可以使用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();
//1。声明你的按钮的纹理,以及其他一些东西(按钮矩形,等等)。
纹理2D我的纹理;
矩形按钮盒;
bool-isMouseIn=false;
//2. 在LoadContent()方法中加载按钮的纹理。
My_texture=Content.Load(“您的资源名称”);
//3. 在Update()方法中处理输入。
MouseState currentMouseState=Mouse.GetState();
if(按钮盒包含(currentMouseState.Position))
{
isMouseIn=true;
}
//4. 在Draw()方法中绘制按钮。
spriteBatch.Begin();
if(isMousein)
{
绘制(我的纹理,按钮盒,颜色,红色;
}
其他的
{
spriteBatch.Draw(我的纹理、纽扣盒、颜色、蓝色);
}
spriteBatch.End();

不过,正如另一个答案所说,最好使用Windows窗体,因为它更适合这样一个简单的程序,并且不需要非常精致或灵活的图形界面。

下面的代码适合我

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

鼠标悬停事件?更可能是
MouseEnter
MouseLeave
事件?