How to change button background image on mouseOver?

前端 未结 4 1267
星月不相逢
星月不相逢 2020-12-19 16:04

I have img1, and img2 in my resources. I have easily set btn.backgroundImage as img1 in btn properties. Images paths are: c:\\Project\\Resources...

Now I don\'t know

4条回答
  •  醉酒成梦
    2020-12-19 16:41

    In the case of winforms:

    If you include the images to your resources you can do it like this, very simple and straight forward:

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

    I would not recommend hardcoding image paths.

    As you have altered your question ...

    There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or 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));
              }
    

    To add images to your resources: Projectproperties/resources/add/existing file

提交回复
热议问题