2008-12-31 62 views
3

我需要顯示一個屏幕或其他東西,說'加載'或任何長時間的過程中工作。在vb.net中顯示加載屏幕

我正在使用Windows Media Encoder SDK創建應用程序,初始化編碼器需要一段時間。我想要一個屏幕在啓動編碼器時彈出「加載」,然後在編碼器完成時它會消失,並且它們可以繼續使用該應用程序。

任何幫助,將不勝感激。謝謝!

回答

9

創建一個將用作「加載」對話框的窗體。當您準備初始化編碼器時,使用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() 

有更優雅的實現並遵循更好的實踐,但這是最簡單的。

0

有很多方法可以做到這一點。最簡單的方法可能是顯示一個模式對話框,然後啓動另一個進程,一旦它完成,然後關閉顯示的對話框。您將需要處理標準X的顯示以關閉。但是,在標準UI線程中這樣做會鎖定用戶界面直到操作完成。

另一種選擇可能是有一個「加載」屏幕,填充默認表單,將它放在前面,然後在輔助線程上觸發長時間運行的進程,一旦完成,您可以通知UI線程並刪除加載屏幕。

這些只是一些想法,它取決於你在做什麼。

+0

@Mitchel我試圖展示一個表單,並且在表單顯示之後,它是否啓動了我的代碼來初始化編碼器......唯一的問題是它不會加載我的標籤,上面寫着Loading,直到編碼器初始化。 – pixeldev 2008-12-31 15:51:22

+0

@Bruno - 這是由於我提到的UI線程阻塞。 Application.DoEvents()的調用應該解決這個問題。否則,使用Background Worker的多線程方法是最好的選擇。 – 2008-12-31 15:55:08

0

你可以嘗試兩件事。

設置您的標籤(如對米切爾的評論中提及)後調用Application.DoEvents()

你有另一種選擇是運行初始化代碼在BackgroundWorker的過程中,編碼器。

+0

關於後臺工作進程的好例子?我現在正在Google上搜尋;) – pixeldev 2008-12-31 15:55:46