我在 Visual Studio 2010 中创建了一个默认表单,并且在表单设计上我没有更改任何内容。我只添加了以下代码Form1.cs
:
using System;
using System.Windows.Forms;
namespace WinFormTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.TopMost = true;
this.ShowInTaskbar = true;
this.Load += new EventHandler(Form1_Load);
this.Shown += new EventHandler(Form1_Shown);
}
void Form1_Load(object sender, EventArgs e)
{
this.Opacity = 0;
}
void Form1_Shown(object sender, EventArgs e)
{
this.Opacity = 1;
}
}
}
启动此程序,表单不会出现在任务栏上。它仅在激活任何其他窗口时才会出现在任务栏上,然后激活此表单。
这种行为的原因是什么?
编辑:
为什么我需要在处理程序 Form1_Load 中设置它的不透明度?我创建了FormAppearingEffect
以下代码的类:
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace AG.FormAdditions
{
public class FormAppearingEffect
{
private Form form;
double originalOpacity;
public FormAppearingEffect(Form form)
{
this.form = form;
form.Load += form_Load;
form.Shown += form_Shown;
}
void form_Load(object sender, EventArgs e)
{
originalOpacity = form.Opacity;
form.Opacity = 0;
}
private void form_Shown(object sender, EventArgs e)
{
try
{
double currentOpacity = 0;
form.Opacity = currentOpacity;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 1; currentOpacity < originalOpacity; i++)
{
currentOpacity = 0.1 * i;
form.Opacity = currentOpacity;
Application.DoEvents();
//if processor loaded and does not have enough time for drawing form, then skip certain count of steps
int waitMiliseconds = (int)(50 * i - stopwatch.ElapsedMilliseconds);
if (waitMiliseconds >= 0)
Thread.Sleep(waitMiliseconds);
else
i -= waitMiliseconds / 50 - 1;
}
stopwatch.Stop();
form.Opacity = originalOpacity;
}
catch (ObjectDisposedException) { }
}
}
}
在任何形式的程序中,我都像这样使用这个类:
using System;
using System.Windows.Forms;
using AG.FormAdditions;
namespace WinFormTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FormAppearingEffect frmEffects = new FormAppearingEffect(this);
}
}
}
因此,我的表格“逐渐”出现在屏幕上。
这是我发现一个错误的地方,我们在这个主题中。就是这个原因,我需要在事件处理程序中设置不透明度。