BLOG.CSHARPHELPER.COM: Grow and shrink buttons when the mouse moves over them in C#
Grow and shrink buttons when the mouse moves over them in C#
This example produces an interesting visual effect by growing buttons when the mouse moves over them and then shrinking them to normal size when the mouse leaves. The technique is remarkably simple.
The program's form contains a FlowLayoutPanel that contains the buttons. The panel automatically rearranges the buttons as they resize so you don't need to write any code for that.
When the form loads, the following code saves sizes and fonts that it will use to resize the buttons.
// The small and large button sizes.
private Size SmallSize, LargeSize;
private Font SmallFont, LargeFont;
// Set the small and large sizes.
private void Form1_Load(object sender, EventArgs e)
{
SmallSize = btnOpen.Size;
LargeSize = new Size(
(int)(1.5 * btnOpen.Size.Width),
(int)(1.5 * btnOpen.Size.Height));
SmallFont = btnOpen.Font;
LargeFont = new Font(
SmallFont.FontFamily,
SmallFont.Size * 1.5f,
FontStyle.Bold);
}
This code saves a button's Size and Font properties. It also calculates the Size and Font that the program will use when the mouse is over a button. For this example the large font is also bold. You could also change other button properties such as making the font italic, changing the buttons' ForeColor, or whatever else you like.
When the mouse enters one of the buttons, the following event handler executes.
// Enlarge the button.
private void btn_MouseEnter(object sender, EventArgs e)
{
Button btn = sender as Button;
btn.Size = LargeSize;
btn.Font = LargeFont;
// Play the pop sound.
using (SoundPlayer player = new SoundPlayer(
Properties.Resources.Pop))
{
player.Play();
}
}
This code converts the sender into a Button and sets its size and font. It then plays the Pop sound effect file that I loaded into the project as a resource at design time.
When the mouse leaves a button, the following event handler executes.
This code resets the button's size and font to their original values.
That's all there is to this. Note that this sort of effect gives some variation to a program but may annoy some users, particularly business users who really aren't interested in cute effects.
Comments