Button Effects Using Mouse Events

Say for example you want to create a button that when the mouse cursor hovers over it the button gets bigger and highlighted. Well, in C# if you want to make the button bigger one way to do it would be to use two Mouse events, MouseEnter and MouseLeave.

First you'll have to set the size and location of your button. Then, in the MouseEnter event assigned to the button you'll have to change the location of the button (usually it's about 4-10 pixels on both axis) and then you'll also have to increase the button's size 2 times the amount of pixels you moved it (on both axis - this way the button will remain in the same position). Finally, in the MouseLeave event (also assigned to the button) you will have to return the button to its original location and size.

Following is an example:

public Form1()
{
InitializeComponent();
//sets the size of the form
this.Size = new Size(500, 500);
//sets the Location of the buton
button1.Location = new Point(100, 100);
//sets the suze of the button
button1.Size = new Size(100, 35);
}

private void button1_MouseEnter(object sender, EventArgs e)
{
//updates the button's Location
button1.Location = new Point(96, 96);
//updates the button's Size
button1.Size = new Size(108, 43);
}

private void button1_MouseLeave(object sender, EventArgs e)
{
//returns the button to its initial location
button1.Location = new Point(100, 100);
//returns the button to its normal size
button1.Size = new Size(100, 35);
}

No comments:

Post a Comment