使用C#在表单中动画Gif

Rab*_*bin 5 c#

在我的项目中,每当执行一个漫长的过程时,会显示一个带有小动画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();
   }
}
Run Code Online (Sandbox Code Playgroud)

表单打开时,图像文件不会立即开始动画.当它进行动画处理时,该过程通常是完整的或非常接近完成,这使得动画无用.加载表单后,有没有办法让gif动画?

k.m*_*k.m 4

为什么不使用线程?学习新东西总是个好主意。

您可以简单地将“长进程”放在后台线程中,并使用事件向表示层报告,例如:

// 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
}
Run Code Online (Sandbox Code Playgroud)

这样,您所要做的就是在 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() + "%";
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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