Baran Topal

Baran Topal


April 2024
M T W T F S S
« Feb    
1234567
891011121314
15161718192021
22232425262728
2930  

Categories


fancy closing of a C#

baranbaran

Long ago, I wanted to have a fading effect in my windows form application. Here you go:


public partial class Form1 : Form
{
    bool fading = false;
    bool fadingComplete = false;
    System.Windows.Forms.Timer myTimer = null;

    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnClosing(CancelEventArgs e)
    {
        if (fading && !fadingComplete)
        {
            e.Cancel = true;
            return;
        }

        if (!fading)
        {
            fading = true;
            myTimer = new System.Windows.Forms.Timer();
            myTimer.Interval = 50;
            myTimer.Tick += new EventHandler(myTimer_Tick);
            myTimer.Start();
            e.Cancel = true;
            return;
        }

        base.OnClosing(e);
    }

    void myTimer_Tick(object sender, EventArgs e)
    {
        if (this.Opacity > 0)
        {
            this.Opacity -= 0.1;
        }
        else
        {
            myTimer.Stop();
            fadingComplete = true;
            this.Close();
        }
    }
}

To test, create a new windows forms project and replace the Form1 class with this. You can simplify with the following button:


private void myBtn_Click(object sender, EventArgs e)
        {
            while (this.Opacity > 0)
            {
                this.Opacity -= 0.1;
                Application.DoEvents();
                System.Threading.Thread.Sleep(50);
            }
            this.DialogResult = DialogResult.OK;
        }