我有2个表单,1个MainForm和1个Form2。我试图将Form2显示为MainForm的模态形式和背景。这是我到目前为止所拥有的。
出现默认的MainForm,5秒后,它将从后台线程将Form2显示为Modal表单。我关闭Form2,如果使用ShowDialog再次显示相同的Form2,则表单不是模态的。如何确保显示的Form2始终是模态的?
Public Class MainForm
Dim frm2 As Form2
Private Sub MainForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
frm2 = New Form2()
Dim frmHandle As IntPtr = frm2.Handle
frm2.Button1.Text = "test"
System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf DoSomething), 0)
End Sub
Private Sub DoSomething()
'call show dialog first time
Threading.Thread.Sleep(5000)
If frm2.InvokeRequired Then
frm2.Invoke(New Action(AddressOf frm2.ShowDialog))
Else
frm2.ShowDialog()
End If
'call show dialog second time
If frm2.InvokeRequired Then
frm2.Invoke(New Action(AddressOf frm2.ShowDialog))
Else
frm2.ShowDialog()
End If
End Sub
End Class
答案 0 :(得分:0)
Public Class MainForm
Dim frm2 As Form2
Private Sub MainForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
frm2 = New Form2()
Dim frmHandle As IntPtr = frm2.Handle
frm2.Button1.Text = "test"
System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf DoSomething), 0)
End Sub
Private Sub DoSomething()
Dim myAction as Action(Of System.Windows.Forms.IWin32Window)
'call show dialog first time
Threading.Thread.Sleep(5000)
If Me.InvokeRequired Then
myAction = AddressOf frm2.ShowDialog
Me.Invoke(myAction(Me))
Else
frm2.ShowDialog(Me)
End If
'call show dialog second time
If Me.InvokeRequired Then
myAction = AddressOf frm2.ShowDialog
Me.Invoke(myAction(Me))
Else
frm2.ShowDialog(Me)
End If
End Sub
End Class
您可以使用以下方法缩短代码:
New Action(Of System.Windows.Forms.IWin32Window)(AddressOf frm2.ShowDialog), Me)