1

i have button and i want the button background change when i aim my cursor at the button so i use mouseenter and mouseleave,it work but i want smoother effect when it change the background

sorry for bad english, and i'm green at c# please help me

my script

    private void button1_Click(object sender, EventArgs e)
    {

    }

    private void button1_MouseEnter(object sender, EventArgs e)
    {
        button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.administrator_icon));
    }

    private void button1_MouseLeave(object sender, EventArgs e)
    {
        button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.alhaq));
    }

}

1 Answers1

0

The idea is the same as in this answer. Instead of using a Timer to change the alpha of the BackColor you will want to change the Index of an ImageList of your Button.

Changing it is very similar to the other post:

private void button3_MouseEnter(object sender, EventArgs e)
{
    timer1.Interval = 25;
    timer1.Start();
}

private void button3_MouseLeave(object sender, EventArgs e)
{
    timer1.Stop();
    button3.ImageIndex = 0;
    index = 1;
}

int index = 1;
private void timer1_Tick(object sender, EventArgs e)
{
    index++; ;
    button3.ImageIndex = index;
    if (index >= imageList1.Images.Count)
    { timer1.Stop(); button3.ImageIndex = 1; index = 1; }
}

The differences are in the ImageList. Unless you want to create it frame by frame, a simple routine to create it dynamically will do the job. First you must assign the inactive and the active images to index 0 and 1 respectively. Then calling this will create step extra images from image nr 1:

public void makeTransPix(int steps)
{
    using (Bitmap bmp = new Bitmap(  imageList1.Images[1] )  ) 
    {
        for (int t = 0; t < steps; t++)
        {
            Bitmap tBmp = new Bitmap(bmp.Width, bmp.Height);
            using (var g = Graphics.FromImage(tBmp))
            {
                Rectangle R = new Rectangle(0, 0, bmp.Width, bmp.Height);
                using (var brush = new SolidBrush(button1.BackColor))
                        g.FillRectangle(brush, R);
                var colorMatrix = new ColorMatrix();
                colorMatrix.Matrix33 = t / (float)steps;
                var imageAttributes = new ImageAttributes();
                imageAttributes.SetColorMatrix(
                    colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                g.DrawImage(bmp, R, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, imageAttributes);
            }
            imageList1.Images.Add(tBmp);
        }
    }
}

You can adjust the steps to vary the speed. You can call it in the Form_Shown event. Make sure all image sizes fit and give your ImageList a ColorDepth of 32!

Community
  • 1
  • 1
TaW
  • 53,122
  • 8
  • 69
  • 111