How to Create Effect Winform using AnimateWindow in C#

By FoxLearn 7/19/2024 2:22:36 AM   7.42K
To create an effect in a WinForm using AnimateWindow in C#, you can follow these steps.

C# Fade Form Effect With the AnimateWindow API Function

Open your Visual Studio, then create a new Windows Forms Application project, then drag and drop the Button and PictureBox controls from the Visual studio toolbox to your winform.

c# animation winform

We will use Win32 API to create animation to winform, you should define the animation flags that specify the type of animation to be performed.

// Define animation flags
enum AnimateWindowFlags : uint
{
    AW_HOR_POSITIVE = 0x00000001,
    AW_HOR_NEGATIVE = 0x00000002,
    AW_VER_POSITIVE = 0x00000004,
    AW_VER_NEGATIVE = 0x00000008,
    AW_CENTER = 0x00000010,
    AW_HIDE = 0x00010000,
    AW_ACTIVATE = 0x00020000,
    AW_SLIDE = 0x00040000,
    AW_BLEND = 0x00080000
}

Next, Declare the AnimateWindow method from the user32.dll library.

// Import AnimateWindow method from user32.dll
[DllImport("user32.dll")]
static extern bool AnimateWindow(IntPtr hWnd, int time, AnimateWindowFlags flags);

Adding the click event handler to the Show Form button allows you to add animation to your form.

private void button1_Click(object sender, EventArgs e)
{
    Form1 frm = new Form1();
    AnimateWindow(frm.Handle, 1000, AnimateWindowFlags.AW_ACTIVATE | AnimateWindowFlags.AW_BLEND);
    frm.ShowDialog();
}

Adding the click event handler to the Show Form button allows you to add animation to your form.

private void button2_Click(object sender, EventArgs e)
{
    Form1 frm = new Form1();
    // Apply animation when form loads
    AnimateWindow(frm.Handle, 1000, AnimateWindowFlags.AW_SLIDE | AnimateWindowFlags.AW_CENTER | AnimateWindowFlags.AW_ACTIVATE);
    frm.ShowDialog();
}

Adding the click event handler to the Show Control button allows you to add animation to your control.

private void button3_Click(object sender, EventArgs e)
{
    AnimateWindow(pictureBox1.Handle, 1000, AnimateWindowFlags.AW_SLIDE | AnimateWindowFlags.AW_CENTER | AnimateWindowFlags.AW_HIDE);
}

Adding the click event handler to the Hide Control button allows you to add animation to your control.

private void button4_Click(object sender, EventArgs e)
{
    AnimateWindow(pictureBox1.Handle, 1000, AnimateWindowFlags.AW_SLIDE | AnimateWindowFlags.AW_CENTER | AnimateWindowFlags.AW_ACTIVATE);
}

This example will animate the form sliding, Adjust the flags and parameters according to your desired animation effect.

Related