我需要显示一个屏幕或其他东西,说'加载'或任何长时间的过程中工作。在vb.net中显示加载屏幕
我正在使用Windows Media Encoder SDK创建应用程序,初始化编码器需要一段时间。我想要一个屏幕在启动编码器时弹出“加载”,然后在编码器完成时它会消失,并且它们可以继续使用该应用程序。
任何帮助,将不胜感激。谢谢!
我需要显示一个屏幕或其他东西,说'加载'或任何长时间的过程中工作。在vb.net中显示加载屏幕
我正在使用Windows Media Encoder SDK创建应用程序,初始化编码器需要一段时间。我想要一个屏幕在启动编码器时弹出“加载”,然后在编码器完成时它会消失,并且它们可以继续使用该应用程序。
任何帮助,将不胜感激。谢谢!
创建一个将用作“加载”对话框的窗体。当您准备初始化编码器时,使用ShowDialog()
方法显示此表格。这导致它阻止用户与显示加载对话框的表单进行交互。
加载对话框应该以加载时的编码方式编码,它使用BackgroundWorker
在单独的线程上初始化编码器。这确保加载对话框将保持响应。下面是对话形式可能看起来像一个例子:
Imports System.ComponentModel
Public Class LoadingForm ' Inherits Form from the designer.vb file
Private _worker As BackgroundWorker
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
_worker = New BackgroundWorker()
AddHandler _worker.DoWork, AddressOf WorkerDoWork
AddHandler _worker.RunWorkerCompleted, AddressOf WorkerCompleted
_worker.RunWorkerAsync()
End Sub
' This is executed on a worker thread and will not make the dialog unresponsive. If you want
' to interact with the dialog (like changing a progress bar or label), you need to use the
' worker's ReportProgress() method (see documentation for details)
Private Sub WorkerDoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
' Initialize encoder here
End Sub
' This is executed on the UI thread after the work is complete. It's a good place to either
' close the dialog or indicate that the initialization is complete. It's safe to work with
' controls from this event.
Private Sub WorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
Me.DialogResult = Windows.Forms.DialogResult.OK
Me.Close()
End Sub
End Class
而且,当你准备好显示的对话框中,你会这么做是这样的:
Dim frm As New LoadingForm()
frm.ShowDialog()
有更优雅的实现并遵循更好的实践,但这是最简单的。
有很多方法可以做到这一点。最简单的方法可能是显示一个模式对话框,然后启动另一个进程,一旦它完成,然后关闭显示的对话框。您将需要处理标准X的显示以关闭。但是,在标准UI线程中这样做会锁定用户界面直到操作完成。
另一种选择可能是有一个“加载”屏幕,填充默认表单,将它放在前面,然后在辅助线程上触发长时间运行的进程,一旦完成,您可以通知UI线程并删除加载屏幕。
这些只是一些想法,它取决于你在做什么。
你可以尝试两件事。
设置您的标签(如对米切尔的评论中提及)后调用Application.DoEvents()
你有另一种选择是运行初始化代码在BackgroundWorker的过程中,编码器。
关于后台工作进程的好例子?我现在正在Google上搜寻;) – pixeldev 2008-12-31 15:55:46
@Mitchel我试图展示一个表单,并且在表单显示之后,它是否启动了我的代码来初始化编码器......唯一的问题是它不会加载我的标签,上面写着Loading,直到编码器初始化。 – pixeldev 2008-12-31 15:51:22
@Bruno - 这是由于我提到的UI线程阻塞。 Application.DoEvents()的调用应该解决这个问题。否则,使用Background Worker的多线程方法是最好的选择。 – 2008-12-31 15:55:08