-1

Message Box DialogResult.No を使用すると、フォームを閉じる条件が期待どおりに動作しません。

formclosing イベントは、ドキュメントを閉じる前に保存するかどうかをユーザーに尋ねます。

以下は私の FormClosing イベントです。

    Private Sub PDFViewSimple_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) _ 
Handles Me.FormClosing

            If doc.IsModified Then

                Dim message As String = "The document is modified, would you like to save it?"
                Dim caption As String = "File Not Saved"
                Dim buttons As MessageBoxButtons = MessageBoxButtons.YesNo
                Dim DefaultButton As MessageBoxDefaultButton = MessageBoxDefaultButton.Button1
                Dim icon As MessageBoxIcon = MessageBoxIcon.Question
                Dim result As DialogResult

                ' Displays A MessageBox.
                result = MessageBox.Show(message, caption, buttons, icon, DefaultButton)

                If (result = DialogResult.Yes) Then
                    Me.Save(Me.Text)
                    Me.Close()
                ElseIf (result = DialogResult.No) Then
                    Me.Close()  ''Should I replace with (Application.Exit)
                End If

            End If

    End Sub
4

1 に答える 1

2

そのコードにはあらゆる種類の問題があります。まず、オプションが 2 つしかないことを考えると、ElseIf厳密に間違っているわけではありませんが、使用は無意味です。そうでない場合はYes、 である必要がNoあるため、必要なのはElse:

If (result = DialogResult.Yes) Then
    Me.Save(Me.Text)
    Me.Close()
Else
    Me.Close()
End If

次に、結果に関係なくElse呼び出しているため、 an でも無意味です。Closeあなたがする必要があるのは、をチェックしYes、に固有のことをしてから、関係なくYes呼び出すことだけですClose:

If (result = DialogResult.Yes) Then
    Me.Save(Me.Text)
End If

Me.Close()

最後に、電話をかけてはいけませんCloseFormClosingイベント ハンドラーにいるので、フォームは既に閉じています。フォームを閉じたくない場合にのみ、何かをする必要があります。したがって、必要なのはこれだけです:

If (result = DialogResult.Yes) Then
    Me.Save(Me.Text)
End If

フォームを閉じたくない場合は、に設定e.CancelTrueます。

于 2018-10-15T09:15:12.733 に答える