在VB.NET中显示加载屏幕

4
我需要展示一个屏幕或其他东西,显示“正在加载”或其他类似的内容,以便在长时间的进程运行时使用。
我正在使用Windows Media Encoder SDK创建一个应用程序,并且初始化编码器需要一些时间。我希望当它正在启动编码器时弹出一个屏幕显示“正在加载”,然后在编码器完成并可以继续使用应用程序时消失。
非常感谢您的帮助!
3个回答

11

创建一个表单,用作“加载”对话框。当你准备初始化编码器时,使用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()

有更优雅的实现和更好的实践方法可供遵循,但这是最简单的。


正是我所寻找的。 @Mitchel @Tom Anderson 感谢你们的帮助!每个人的回答确实都帮了我很多! - pixeldev

0

有很多方法可以做到这一点。 最简单的方法可能是显示模态对话框,然后启动其他进程,一旦完成,您就可以关闭显示的对话框。 但是,您需要处理标准 X 关闭的显示。 然而,在标准 UI 线程中完成所有操作会锁定 UI,直到操作完成。

另一个选择可能是拥有一个“加载”屏幕填充默认表单,将其置于前端,然后在第二个线程上触发长时间运行的过程,一旦完成,您可以通知 UI 线程并删除加载屏幕。

这些只是一些想法,它真的取决于您要做什么。


@Mitchel 我尝试显示一个表单,在表单显示后启动我的代码来初始化编码器...唯一的问题是,直到编码器被初始化之后,它才会加载我的标签,上面写着“正在加载”。 - pixeldev
@Bruno - 这是由于我之前提到的UI线程阻塞所致。调用Application.DoEvents()可以解决这个问题。否则,使用Background Worker的多线程方法是最好的选择。 - Mitchel Sellers

0

你可以尝试两件事情。

在设置标签后(如Mitchel的评论中所述),调用Application.DoEvents()

另一个选择是在BackgroundWorker进程中运行编码器的初始化代码。


有关后台工作进程的好例子吗?我正在谷歌搜索中 ;) - pixeldev
这是一个标准组件,可以参考OwenP的回复来获取好的示例。 - Tom Anderson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接