Introduction
In C# we can access to opacity of WinForm by
Opacity
property .
This article shows you how we can do it by a simple project.
Using the code
System.Windows.Forms.Timer
We'd like to make fade-in and fade-out effect in our WinForm.
To do that we used
System.Windows.Forms.Timer
.
We used three Timers in our project :
TimerFadein
: Shows WinApp with fade-in effect.
TimerFadein runs below method in its Tick event.
private void TimerFadein_Tick(object sender, EventArgs e)
{
if (timerHalfFadeOut.Enabled || TimerFadeout.Enabled)
{
TimerFadein.Enabled = false;
return;
}
timerRunning = true;
this.Opacity += 0.05;
if (this.Opacity >= 0.95)
{
this.Opacity = 1;
timerRunning = TimerFadein.Enabled = false;
}
maskedTextBoxOpacity.Text = (this.Opacity * 100).ToString();
hScrollBar1.Value = (int)(this.Opacity * 100);
}
TimerFadeout
: Shows WinApp with fade-out effect.
TimerFadeout runs below method in its Tick event.
private void TimerFadeout_Tick(object sender, EventArgs e)
{
if (timerHalfFadeOut.Enabled || TimerFadein.Enabled)
{
TimerFadeout.Enabled = false;
return;
}
timerRunning = true;
this.Opacity -= 0.05;
if (this.Opacity <= 0.05)
{
this.Opacity = 0;
Application.ExitThread();
}
maskedTextBoxOpacity.Text = (this.Opacity * 100).ToString();
hScrollBar1.Value = (int)(this.Opacity * 100);
}
timerHalfFadeOut
: Shows WinApp with 0.5 opacity and fade-out effect.
timerHalfFadeOut runs below method in its Tick event.
private void timerHalfFadeOut_Tick(object sender, EventArgs e)
{
if (TimerFadeout.Enabled || TimerFadein.Enabled)
{
timerHalfFadeOut.Enabled = false;
return;
}
timerRunning = true;
this.Opacity -= 0.05;
if (this.Opacity <= 0.50)
{
this.Opacity = 0.5;
timerRunning = timerHalfFadeOut.Enabled = false;
}
maskedTextBoxOpacity.Text = (this.Opacity * 100).ToString();
hScrollBar1.Value = (int)(this.Opacity * 100);
}
Running WinApp with Fade-in effect
We'd like to show our project with fade-in effect thus we must change opacity of our Form to zero in constructor method .
We must enable
TimerFadein
too , to show our WinApp with fade-in effect.
public Form1()
{
InitializeComponent();
this.Opacity = 0;
TimerFadein.Enabled = true;
}
Well, other things (like closing WinApp and fade-out effect) are very similar with above method .
Only we must enable or disable Timers.
See source code.
Good luck