Baran Topal

Baran Topal


June 2018
M T W T F S S
« Feb    
 123
45678910
11121314151617
18192021222324
252627282930  

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;
        }