在我的项目中,每当执行一个长流程时,都会显示一个小表单和一个小动画 gif 文件。我使用 this.Show() 打开表单,使用 this.Close() 关闭表单。
以下是我使用的代码。
public partial class PlzWaitMessage : Form
{
public PlzWaitMessage()
{
InitializeComponent();
}
public void ShowSpalshSceen()
{
this.Show();
Application.DoEvents();
}
public void CloseSpalshScreen()
{
this.Close();
}
}
当表单打开时,图像文件不会立即开始动画。当它执行动画时,该过程通常已完成或非常接近完成,这使得动画毫无用处。有没有办法让我在加载表单后立即生成 gif 动画?
为什么不使用线程?学习新东西总是个好主意。
您可以简单地将“长进程”放在后台线程中,并使用事件向表示层报告,例如:
// in your "long process" class
public event Action<double> ReportCompletition;
// this method will start long process in separate background thread
public void Start()
{
Thread thread = new Thread(this.LongProcess);
thread.IsBackground = true;
thread.Start();
}
private void LongProcess()
{
// do something
// report 10% completition by raising event
this.ReportCompletition(0.1);
// do something more
this.ReportCompletition(0.5);
// ... and so on
}
这样,您所要做的就是在 Form/UI 中实现简单的方法,该方法将消耗这些信息。
public partial class MainApplicationWindow : Form
{
private LongProcessClass _longProcess;
public MainApplicationWindow
{
this.InitializeComponent();
this._longProcess = new LongProcessClass();
// bind UI updating method to long process class event
this._longProcess.ReportCompletition += this.DisplayCompletitionInfo;
}
private void DisplayCompletitionInfo(double completition)
{
// check if control you want to display info in needs to be invoked
// - request is coming from different thread
if (control.InvokeRequired)
{
Action<double> updateMethod = this.DisplayCompletitionInfo;
control.Invoke(updateMethod, new object[] { completition });
}
// here you put code to do actual UI updating,
// eg. displaying status message
else
{
int progress = (int) completition * 10;
control.Text = "Please wait. Long process progress: "
+ progress.ToString() + "%";
}
}
当然,您可以在漫长的过程中报告您喜欢的任何内容。无论是完成率、准备显示字符串消息等等。您还可以使用事件来报告长流程已完成、中断或您希望的任何长流程数据。
有关此主题的更多详细信息,您可能需要查看 MSDN 教程螺纹加工 http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx and Events http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)