Invoke form showdialog is not modal

1.4k views Asked by At

I have 2 forms, 1 MainForm and 1 Form2. I am trying to display Form2 as a modal form and background from MainForm. Here's what I have so far.

The default MainForm appears and after 5 seconds it will show Form2 as a Modal form from a background thread. I close Form2 and if the same Form2 shows up again using ShowDialog, the form is not modal. How do I make sure that the Form2 that shows up is always modal?

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
1

There are 1 answers

7
Keith Mifsud On BEST ANSWER

in the showDialog, you can set the parent form which causes the child to become modal:

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

You can shorten the code by using:

New Action(Of System.Windows.Forms.IWin32Window)(AddressOf frm2.ShowDialog), Me)