使用C#在表单中动画Gif

在我的项目中,每当执行一个很长的过程时,会显示一个带有小动画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 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 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() + "%"; } } 

当然,您可以在漫长的过程中报告您喜欢的任何内容。 是它的completition率,准备显示字符串消息,任何东西。 您还可以使用事件来报告长流程已完成,损坏或您希望的任何长流程数据。

有关此主题的更多详细信息,您可能需要查看有关线程和事件的 MSDN教程。

你应该在一个单独的线程中做“漫长的过程”。 我建议使用BackgroundWorker 。

这将使您的代码更加困难。 其中一个主要原因是,您无法从后台线程与UI进行通信。

另请注意链接页面的警告:

警告

当使用任何类型的multithreading时,您可能会暴露自己非常严重和复杂的错误。 在实现使用multithreading的任何解决方案之前,请参阅托管线程最佳实践。

如果这太困难,您可以从“长进程”代码中非常频繁地调用Application.DoEvents。

无论您选择什么,这都将使用户可以与您的表单进行交互。 比如关闭它。 你应该知道这一点。

在PictureBox中使用gif,并使用Form pWait = new Form(); pWait.Show();打开它Form pWait = new Form(); pWait.Show(); Form pWait = new Form(); pWait.Show();