I want to change the background image based on mouseenter and mouseleave events to achieve a mouseover effect for the buttons. What is the simplest way of achieving this (preferably in a manner so that the button can be inherited)?
+1
A:
private void Form1_Leave(object sender, System.EventArgs e)
{
this.BackgroundImage=Image.FromFile("file1");
}
private void Form1_MouseEnter(object sender, System.EventArgs e)
{
this.BackgroundImage=Image.FromFile("file2");
}
RV
2009-07-18 11:11:31
thanks a lot for showing how to load images from file. I am new to VC# so wasn't sure how to achieve this.
2009-07-24 11:14:50
+1
A:
You can create a new class, inheriting from Button, and override OnMouseEnter
and OnMouseLeave
. Give it a property so that you can set which background image it should get when the mouse enters, and you are good to go.
Full working example (with a couple of design-time support attributes added):
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
namespace WindowsFormsApplication1
{
class HighlightButton : Button
{
[Category("Appearance")]
[Description("The background image that the Button should have when the mouse is over a visible part of it.")]
public Image MouseoverBackgroundImage { get; set; }
// property to hold the original background image while the mouse-over
// image is displayed, so that we can restore it when the mouse leaves
protected Image OriginalBackgroundImage { get; set; }
protected override void OnMouseEnter(EventArgs e)
{
this.OriginalBackgroundImage = this.BackgroundImage;
this.BackgroundImage = this.MouseoverBackgroundImage;
base.OnMouseEnter(e);
}
protected override void OnMouseLeave(EventArgs e)
{
this.BackgroundImage = this.OriginalBackgroundImage;
base.OnMouseLeave(e);
}
}
}
Edit: realized that my initial sample changed the BackColor, not the BackgroundImage. Fixed that.
Fredrik Mörk
2009-07-18 11:29:34