次のイベント/メソッドをさらに調査すると、次のパターンが明らかになりました。 Leave (コントロール上) ProcessDialogKey (フォーム上およびコントロール上) ProcessDataGridViewKey (コントロール上)
最後の 2 つのイベントが問題の鍵であることが判明しました。
100% .NET プロジェクトでテストしたところ、内部でタブ移動すると ProcessDataGridViewKey イベントが実行されて発生することがわかりました。最後のセルでは、ProcessDataGridView 関数は実行されませんでしたが、ProcessDialogKey 関数は実行されました。
Interop プロジェクトでテストしたとき、イベントはまったく同じでしたが、ProcessDataGridViewKey 関数が実行される前に、コントロールの Leave イベントが発生しました。悪いシナリオは、コントロールにフォーカスがなく、ProcessDataGridViewKey 関数が実行されるという点で独特です。
おそらく、それをテストして、フォーカスをコントロールに戻すことができるでしょうか? できることがわかりました。これを処理するサブクラス化されたコントロールを次に示しますが、100% .NET プロジェクトでも問題なく動作します。
Public Class DataGridViewCustom : Inherits DataGridView
Protected Overrides Function ProcessDataGridViewKey(e As System.Windows.Forms.KeyEventArgs) As Boolean
' When the grid is hosted by a form that is being loaded through the Interop Forms Toolkit,
' the default behavior of using the TAB key to navigate between cells is broken
' (StandardTab = False). The tab key causes the grid control to lose focus before it has a
' chance to process the tab key in this event handler.
'
' This handler is not executed when the TAB key is supposed to make it lose focus (i.e. when
' StandardTab is True or when TABbing off the last cell within the grid). In those
' scenarios, the ProcessDialogKey event handler is executed, and there is no problem.
' Therefore, we can assume that if this event is being processed, and the grid does not have
' focus, we should put focus back on the control.
' The datagridview has different behavior for TAB and CTL-TAB, depending on how the StandardTab
' property is set. We don't have to worry about that becuase this method only executes when the
' focus is supposed to stay within the control. A different method is executed when the focus
' is supposed to leave the control.
If e.KeyCode = Keys.Tab AndAlso Not Me.Focused Then Me.Focus()
Return MyBase.ProcessDataGridViewKey(e)
End Function
End Class