我已经在表单属性中将KeyPreview设置为true
我正在开发一个小程序,我遇到一个问题,当我按下并释放任何箭头键时,组件盒内部的某些控件似乎没有触发我的表单上的KeyDown事件,只是KeyUp事件.我的代码是否有问题可能导致此问题?
具体来说,我在表单上启用了KeyPreview,并在两个子程序中的e.SuppressKeyPress = True上设置断点,只有frmMain_KeyUp的断点点击断点.
我添加了两个GroupBox事件,希望可以缓解这个问题,但没有这样的运气.但是,我在表单上有一个自定义控件,专门编码忽略这些按键,代码按预期工作.
Private Sub frmMain_KeyDown(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown,GroupBox1.KeyDown,GroupBox2.KeyDown e.SuppressKeyPress = True Select Case e.KeyCode Case Keys.Left ScrollDir = ScrollDir Or 1 Case Keys.Right ScrollDir = ScrollDir Or 2 Case Keys.Down ScrollDir = ScrollDir Or 4 Case Keys.Up ScrollDir = ScrollDir Or 8 Case Else e.SuppressKeyPress = False End Select tScroll.Enabled = True tScroll_Tick(Nothing,Nothing) End Sub Private Sub frmMain_KeyUp(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp,GroupBox1.KeyUp,GroupBox2.KeyUp e.SuppressKeyPress = True Select Case e.KeyCode Case Keys.Left ScrollDir = ScrollDir And (Not 1) Case Keys.Right ScrollDir = ScrollDir And (Not 2) Case Keys.Down ScrollDir = ScrollDir And (Not 4) Case Keys.Up ScrollDir = ScrollDir And (Not 8) Case Else e.SuppressKeyPress = False End Select If ScrollDir = 0 Then tScroll.Enabled = False End Sub
Private Sub TileDropDown_KeyDown(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown If e.KeyValue = 40 OrElse e.KeyValue = 38 OrElse e.KeyValue = 39 OrElse e.KeyValue = 37 Then e.SuppressKeyPress = True End If End Sub
某些控件拦截keydown事件中的箭头键,但不在keyup事件中.一种解决方案是派生控件类并重写ProcessCmdKey:
原文链接:https://www.f2er.com/vb/255894.htmlProtected Overrides Function ProcessCmdKey(ByRef msg As Message,ByVal keydata As Keys) As Boolean If keydata = Keys.Right Or keydata = Keys.Left Or keydata = Keys.Up Or keydata = Keys.Down Then OnKeyDown(New KeyEventArgs(keydata)) ProcessCmdKey = True Else ProcessCmdKey = MyBase.ProcessCmdKey(msg,keydata) End If End Function