不用意に押されたクリックやキーで次の画面に遷移した時に意図しない動作を抑制したい時
Imports System.Runtime.InteropServices Public Class clsKeyBuff <DllImport("user32.dll", SetLastError:=True)> Private Shared Function PeekMessage( ByRef lpMsg As MSG, ByVal hwnd As Int32, ByVal wMsgFilterMin As Int32, ByVal wMsgFilterMax As Int32, ByVal wRemoveMsg As PeekMsgOption ) As Boolean End Function <DllImport("user32.dll", SetLastError:=True)> Private Shared Function TranslateMessage(ByRef lpMsg As MSG) As Boolean End Function <DllImport("user32.dll", SetLastError:=True)> Private Shared Function DispatchMessage(ByRef lpMsg As MSG) As Int32 End Function Private Enum PeekMsgOption PM_NOREMOVE = 0 ' 削除しない PM_REMOVE ' 削除する End Enum <StructLayout(LayoutKind.Sequential)> Structure MSG Public HWnd As Int32 Public Msg As Int32 Public WParam As Int32 Public LParam As Int32 Public Time As Int32 Public Pt As POINTAPI End Structure 'MSG <StructLayout(LayoutKind.Sequential)> Structure POINTAPI Public x As Int32 Public y As Int32 End Structure Const PM_REMOVE = &H1 Const WM_KEYFIRST = &H100 Const WM_KEYLAST = &H108 Const WM_MOUSEFIRST = &H200 Const WM_MOUSELAST = &H20A ''' <summary> ''' キーバッファクリア ''' </summary> ''' <param name="frm">フォームオブジェクト</param> Public Shared Sub clearBuff(frm As Form) Try Dim m As New MSG Do While PeekMessage(m, CInt(frm.Handle), WM_KEYFIRST, WM_KEYLAST, PeekMsgOption.PM_REMOVE) Loop Do While PeekMessage(m, CInt(frm.Handle), WM_MOUSEFIRST, WM_MOUSELAST, PeekMsgOption.PM_REMOVE) Loop Catch ex As Exception End Try End Class
キーバッファをクリアしたいイベント箇所に
clsKeyBuff.clearBuff(Me)
これだけでキーバッファはクリアされて意図しない動作を抑制できます。