如何在表单上禁用空格键,按键 - VB.NET

时间:2015-08-06 08:48:28

标签: vb.net

我试过这一切,但似乎无法找到任何解决方案。

我想要做的是禁止空格键成为可用的键,因为它干扰了我游戏的功能。

另外要澄清这一点需要通过表单屏幕上的keypreview而不是文本框来完成。

我想禁止使用空格键作为可检测的按键。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:2)

我找到了这个问题的答案;要做到这一点,你需要将keydown事件处理程序添加到你想要禁用密钥的控件。然后输入代码:

If e.KeyCode = Keys.space Then
    e.SuppressKeyPress = True
End If

这也适用于其他键,例如输入键和其他键。只需将"keys."更改为您要禁用/禁用的键。

答案 1 :(得分:0)

使用Key Hooking机制。

示例在VB HereHere

示例在C#HereLow-level Windows API hooks from C# to stop unwanted keystrokes

如果您不熟悉C#,可以使用code converter从VB获取源代码以理解代码。但有些时候没有100%转换。

完整代码

要使用此代码:将CheckBox和TextBox插入Win Form

Public Class Form1
    Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Integer, ByVal lpfn As LowLevelKeyboardProcDelegate, ByVal hMod As IntPtr, ByVal dwThreadId As Integer) As IntPtr
    Declare Function UnhookWindowsHookEx Lib "user32" Alias "UnhookWindowsHookEx" (ByVal hHook As IntPtr) As Boolean
    Declare Function CallNextHookEx Lib "user32" Alias "CallNextHookEx" (ByVal hHook As IntPtr, ByVal nCode As Integer, ByVal wParam As Integer, ByRef lParam As KBDLLHOOKSTRUCT) As Integer
    Delegate Function LowLevelKeyboardProcDelegate(ByVal nCode As Integer, ByVal wParam As Integer, ByRef lParam As KBDLLHOOKSTRUCT) As Integer

    Const WH_KEYBOARD_LL As Integer = 13

    Structure KBDLLHOOKSTRUCT
        Dim vkCode As Integer
        Dim scanCode As Integer
        Dim flags As Integer
        Dim time As Integer
        Dim dwExtraInfo As Integer
    End Structure

    Dim intLLKey As IntPtr
    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked Then
            intLLKey = SetWindowsHookEx(WH_KEYBOARD_LL, AddressOf LowLevelKeyboardProc, IntPtr.Zero, 0)
        Else
            UnhookWindowsHookEx(intLLKey)
        End If

    End Sub
    Private Function LowLevelKeyboardProc(ByVal nCode As Integer, ByVal wParam As Integer, ByRef lParam As KBDLLHOOKSTRUCT) As Integer
        Dim blnEat As Boolean = False

        Select Case wParam
            Case 256, 257, 260, 261
                'Alt+Tab, Alt+Esc, Ctrl+Esc, Windows Key    
                blnEat = ((lParam.vkCode = 9) AndAlso (lParam.flags = 32)) Or _
                ((lParam.vkCode = 27) AndAlso (lParam.flags = 32)) Or _
                ((lParam.vkCode = 27) AndAlso (lParam.flags = 0)) Or _
                ((lParam.vkCode = 91) AndAlso (lParam.flags = 1)) Or _
                ((lParam.vkCode = 92) AndAlso (lParam.flags = 1)) Or _
                ((lParam.vkCode = 32) AndAlso (lParam.flags = 0)) 'this is the space key code 32

        End Select

        If blnEat = True Then
            Return 1
        Else
            Return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam)
        End If
    End Function

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        UnhookWindowsHookEx(intLLKey)
    End Sub
End Class