2

デスクトップ アプリケーション用の vb.net で、閉じる前にドキュメントを完全に保存する関数を作成し、System.Threading.Timer で実装しました。

あなたがそれをどのように経験したかについて、好意的に尋ねています。

そこで、閉じる前にドキュメントを保存するタイマーを作りました。

ただし、タイマーを使用せずに関数またはハンドラーを 1 回呼び出すだけでテストすると、保存するかどうか、またはキャンセルを求めるダイアログ ボックスが表示されるため、ドキュメントは閉じる前に保存されません。

本当にタイマーが必要ですか?タイマーがシステムを 1 ミリ秒も遅らせる可能性があることを知っているからです。

タイマーを 100 ミリ秒に設定しました。

しかし、私はタイマーを使いたくありません。関数を1回呼び出すだけで閉じる前にドキュメントを保存したいのです。

それは本当にタイマーを使用していますか?または、1 つのコール設定だけで実行できますか?

1 回の関数呼び出しで実行できる場合は、コードが不足していると思います。

ご意見、ご経験ありがとうございます。

4

1 に答える 1

1

FormClosing イベントを処理できます。ハンドラーでは、フォームが閉じる前にアクションを実行でき、閉じるイベントをキャンセルすることもできます。次に例を示します。

Dim Saved As Boolean = False

Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If Not Saved Then
        Dim Result As DialogResult = MessageBox.Show("Do you want to save your text?", "Save Text?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
        Select Case Result
            'Since pressing the No button will result in closing the form without
            'saving the text we don't need to handle it here
            Case Windows.Forms.DialogResult.Yes

                SaveText_Click()
            Case Windows.Forms.DialogResult.Cancel
                e.Cancel = True
        End Select
    End If
End Sub

Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
    Saved = False
End Sub
'SaveText is a button for the user to manually save the text on demand.
'Since we don't need the sender or the eventargs, we can handle the click event without them.
'this way we can call this like any sub without having to worry about providing the right parameters.
Private Sub SaveText_Click() Handles SaveText.Click
    'Add your procedure to save the text here
    Saved = True
End Sub

保存せずにオプションを閉じたくない場合は、メッセージボックスと選択ブロックを省略し、SaveText() を呼び出して、そこにデータを保存するコードを含めます。

于 2013-06-16T21:20:18.753 に答える