gpt4 book ai didi

vb.net - KeyDown 事件未通过 .NET WinForms 触发?

转载 作者:行者123 更新时间:2023-12-03 00:50:51 24 4
gpt4 key购买 nike

我已经 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:

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

关于vb.net - KeyDown 事件未通过 .NET WinForms 触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1608611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com