1

フォームの右上にある赤い X がクリックされたときに、コードでケースを処理したいと考えています。この目的のために、私はこれを参考にして、次のようにイベントハンドラーを作成しました:-

Private Sub DoFoo (sender As System.Object, e As System.EventArgs) _
                   Handles Me.FormClosing
    ' Do things
End Sub

しかし、(ブレークポイントの設定から)特定のフォームでは、赤いXがクリックされたときにこのイベントハンドラーが呼び出されないことがわかりましたが、他のフォームではそうです。フォームはすべて System.Windows.Forms.Form 型ですが、ほとんどの点で当然異なります。これを引き起こしている可能性のあるものと、それに対して何をすべきかを誰かが知っていますか?

編集

Vitor の質問への回答として、機能しないフォームは次のように作成されます。

If my_form Is Nothing Then
    my_form = New MyForm(parameters)
    my_form.Title = "Contour Plot Options"
Else
    my_form.BringToFront
End If

my_form.Show

期待どおりに動作しているものは、次のように作成されます:-

If my_working_form Is Nothing Then
    my_working_form = New MyWorkingForm
End If

my_working_form.Show

Visibleどこにも設定またはクリアするプロパティが表示されません。

4

2 に答える 2

3

パラメータが正しくありません。FormClosing イベントには FormClosingEventArgs 引数があります。

Private Sub DoFoo(ByVal sender As Object, ByVal e As FormClosingEventArgs) _
                  Handles Me.FormClosing
    If (e.CloseReason = CloseReason.UserClosing) Then

    End If
End Sub

プロパティ `CloseReason' の e 変数を調べることができます。これには、ユーザーがフォームを閉じたことを意味する UserClosing 列挙型が含まれます。

各フォームは、独自の FormClosing イベントを処理する必要があります。イベントをサブスクライブする代わりに、次のようにオーバーライドする方が良いと思います。

Protected Overrides Sub OnFormClosing(ByVal e As FormClosingEventArgs)
  If (e.CloseReason = CloseReason.UserClosing) Then

  End If
  MyBase.OnFormClosing(e)
End Sub
于 2012-11-05T15:46:59.927 に答える
1

AddHandlerフォームをインスタンス化する場合は、サブスクライブするイベントを覚えておく必要があります。

my_form = New MyForm(parameters)
my_form.Title = "Contour Plot Options"
AddHandler my_form.Closing, AddressOf MyForm_Closing

'...

Sub MyForm_Closing(s As Object, ByVal e As FormClosingEventArgs)
   '...
End Sub

もちろん、メモリ リークを回避するには、次のようにする必要があります。

'global code
Private myFormClosingEventHandler As FormClosedEventHandler = Nothing
'...

Private Sub CreateForm
    my_form = New MyForm(parameters)
    my_form.Title = "Contour Plot Options"

    myFormClosingEvent = New FormClosedEventHandler(AddressOf MyForm_Closing)
    AddHandler my_form.Closing, myFormClosingEventHandler
    '...
End Sub

Sub MyForm_Closing(s As Object, ByVal e As FormClosingEventArgs)
    RemoveHandler my_form.Closing, myFormClosingEventHandler
   '...
End Sub

または、代わりにクラスでこれを行うことで、すべてを事前に初期化することができます。

Private WithEvents my_form1 As Form = New Form()
Private WithEvents my_form2 As Form = New Form()
'... etc.

AddHandlerこれで、 andを使用せずに、いつものように Handle キーワードを使用してコード ハンドラーを追加できますRemoveHandler

Protected Sub my_form1_Closing(s as object, e as FormClosingEventArgs) _
    Handles my_form1.Closing
    '...
End Sub
于 2012-11-05T23:12:39.420 に答える