如何在mouseOver上更改按钮背景图像?

Sla*_*isa 3 c# image button

我的资源中有img1和img2.我很容易在btn属性中将btn.backgroundImage设置为img1.图像路径是:c:\ Project\Resources ...

现在我不知道如何将btn.backgroundImage设置为img2,我想在事件"MouseEnter"上进行.所以我会提供完整的代码,因为我对此非常了解......

我赞成任何给定的想法......

Sam*_*cke 17

在winforms的情况下:

如果您将图像包含在资源中,您可以这样做,非常简单直接:

public Form1()
          {
               InitializeComponent();
               button1.MouseEnter += new EventHandler(button1_MouseEnter);
               button1.MouseLeave += new EventHandler(button1_MouseLeave);
          }

          void button1_MouseLeave(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
          }


          void button1_MouseEnter(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }
Run Code Online (Sandbox Code Playgroud)

我不建议硬编码图像路径.

正如你改变了你的问题......

在winforms afai中没有(on)MouseOver,有MouseHover和MouseMove事件,但如果你改变那些图像,它将不会改变回来,所以MouseEnter + MouseLeave是你想要的.无论如何,在Hover或Move上更改图像:

in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover); 
button1.MouseMove += new MouseEventHandler(button1_MouseMove);

void button1_MouseMove(object sender, MouseEventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

          void button1_MouseHover(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }
Run Code Online (Sandbox Code Playgroud)

要向资源添加图像:Projectproperties/resources/add/existing file