从后台线程显示消息框模式

时间:2015-04-16 07:41:28

标签: vb.net winforms messagebox ui-thread background-thread

在我的Winform VB.NET应用程序中,我正在检查一些字段。如果一个特定字段等于true,我需要显示消息。通常它会是这样的:

If (myField) Then
     MessageBox.Show("Something is wrong", "Warning", MessageBoxButtons.OK)

    // continuing...
End If

此消息必须以modaly方式显示(用户只有在单击“确定”按钮后才能返回主窗体)。问题是我不希望线程等待点击(只显示消息并继续 - 不要等待OK按钮)。

我唯一的想法是在后台线程中显示消息:

If (myField) Then
     Dim t As Thread = New Thread(AddressOf ShowMyMessage)
     t.Start()

     // continuing...
End If

Private Sub ShowMyMessage()
     MessageBox.Show("Something is wrong", "Warning", MessageBoxButtons.OK)
End Sub

但是在这种情况下,消息没有以modaly方式显示(用户可以返回主窗体并与之交互而无需单击“确定”按钮)。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果你想做的话,你的设计可能会出错,但是为了练习,我写了一些应该达到你想要的东西。

Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
    Dim thr As New Thread(Sub() ThreadTest())
    thr.Start()
End Sub

Private Sub ThreadTest()
    Debug.WriteLine("Started")
    Me.ShowMessageBox("Can't click on the main form now", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    Debug.WriteLine("Thread continued")
End Sub

Public Sub ShowMessageBox(textToShow As String, caption As String, buttons As MessageBoxButtons, icon As MessageBoxIcon)
    Me.BeginInvoke(Sub() MessageBox.Show(textToShow, caption, buttons, icon))
End Sub

运行它时,您将看到ThreadTest代码继续显示消息框,但在主消息框上单击确定之前,不允许与主窗体进行交互

相关问题