我已经在表单属性中将 KeyPreview
设置为true
我正在开发一个小程序,我遇到一个问题,当我按下并释放任何箭头键时,看起来它在groupboxes中的某些控件没有触发我表单上的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
答案 0 :(得分:9)
某些控件拦截keydown事件中的箭头键,但不在keyup事件中。一种解决方案是派生控件类并重写ProcessCmdKey:
Protected 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
答案 1 :(得分:0)
无需做太多事情,只需在加载函数中使用Me.KeyPreview = True并在vb.net的Target函数中为箭头键使用(处理Me.KeyUp)