Question

frmMain

DoSomething()
My.Forms.frmMessage.ShowDialog(Me)
If AcceptButtonClicked Then
' Do Code
DoCode()
Else
' Cancel Button Pressed
DoOtherCode()
End If
DoMore()

frmMessage

My.Forms.frmMain.AcceptButtonClicked = True

Is there a way to pass a value from a Dialog window back to a paused thread on the main window? I want to know if they pressed the Ok or Cancel Button after filling out a form that pops up.

Was it helpful?

Solution

You can use the DialogResult property on your form. This value will be returned by the ShowDialog function you call. You can also set this property on your buttons so WinForms will handle the setting of the form property.

In your frmMessage you'll have to set the property accordingly (pick the one you need, OK and Cancel). Then you can check the return value easily:

If My.Forms.frmMessage.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
    ' OK button pressed
    DoCode()
Else
    ' Cancel button pressed
    DoOtherCode()
End If

Don't forget that the user might be able to close the form in another way than closing it with your buttons (e.g. by closing it with the close button).

OTHER TIPS

You should set the AcceptButton and the CancelButton property on the Form, but also, the AcceptButton should have its property DialogResult set to OK and the CancelButton to Cancel.

In this way, when your user presses one of these buttons the ShowDialog call returns and you can check the return value using the predefined values in the enum DialogResult

DoSomething()
Dim result = My.Forms.frmMessage.ShowDialog(Me)
If result = DialogResult.OK Then
   ' Do Code
   DoCode()
Else
  ' Cancel Button Pressed
   DoOtherCode()
End If
DoMore()

The answers by Styxxy and Steve both work for handling the DialogResult in the main window. However the DialogResult property for the Accept button should not be set in the properties window, it should be set in your code after validation occurs. This way if the user inputs bad data in the form they can get an error message and fix it without losing any work, instead of starting over.

'code in Dialog Form
Private Sub btnAccept_Click(sender As System.Object, e As System.EventArgs) Handles btnAccept.Click
    If IsValid() = True Then
        DialogResult = Windows.Forms.DialogResult.OK
    End If
End Sub

Me.DialogResult = Windows.Forms.DialogResult.Abort Me.Close()

and it will return result Abort

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top