【发布时间】:2008-12-31 15:26:16
【问题描述】:
我需要显示一个屏幕或其他东西,说“正在加载”或其他什么,而长时间的过程正在运行。
我正在使用 Windows Media Encoder SDK 创建一个应用程序,初始化编码器需要一段时间。我希望在启动编码器时弹出一个屏幕说“正在加载”,然后在编码器完成后消失,他们可以继续使用应用程序。
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: vb.net visual-studio visual-studio-2005
我需要显示一个屏幕或其他东西,说“正在加载”或其他什么,而长时间的过程正在运行。
我正在使用 Windows Media Encoder SDK 创建一个应用程序,初始化编码器需要一段时间。我希望在启动编码器时弹出一个屏幕说“正在加载”,然后在编码器完成后消失,他们可以继续使用应用程序。
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: vb.net visual-studio visual-studio-2005
创建一个用作“加载”对话框的表单。当您准备好初始化编码器时,使用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,直到操作完成。
另一个选项可能是有一个“加载”屏幕来填充您的默认表单,将其带到前面,然后在辅助线程上触发长时间运行的进程,一旦完成,您可以通知 UI 线程并删除加载屏幕。
这些只是一些想法,这真的取决于你在做什么。
【讨论】:
你可以尝试两件事。
设置标签后(如对 Mitchel 的评论中所述)致电 Application.DoEvents()
另一个选择是在 BackgroundWorker 进程中运行编码器的初始化代码。
【讨论】: