Title: Make pop buttons in C#
This example produces an interesting visual effect that I call "pop buttons." The buttons grow and shrink when the mouse moves over them. The technique is remarkably simple and adds some extra interactivity to an otherwise ordinary program.
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 sound effect.
private SoundPlayer PopPlayer =
new SoundPlayer(Properties.Resources.Pop);
// 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 change other button properties such as making the font italic, changing the buttons' ForeColor property, 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.
PopPlayer.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 pop button, the following event handler executes.
// Shrink the button.
private void btn_MouseLeave(object sender, EventArgs e)
{
Button btn = sender as Button;
btn.Size = SmallSize;
btn.Font = SmallFont;
}
This code resets the button's size and font to their original values.
That's all there is to it. 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.
Download the example to experiment with it and to see additional details.
|