簡體   English   中英

C#:如何在文本框的 keydown 事件中禁止按鍵被無限按下?

[英]C#: How do you disable a key from being pressed indefinetly in textbox's keydown event?

C#:如何在文本框的 keydown 事件中禁止按鍵被無限按下?

處理該問題的標准方法是為Textbox.KeyDown事件創建一個事件處理程序,然后在按下的鍵與您要禁用的鍵匹配時將KeyEventArgs.SuppressKeyPress設置為 true。 這是一個例子:

yourTextBox.KeyDown += delegate(Object sender, KeyEventArgs e)
{
    e.SuppressKeyPress = (e.KeyCode == YOUR_KEY);
}

使用 e.SuppressKeyPress 將完全阻止按鍵記錄。

假設您希望注冊第一個擊鍵,但在用戶按住它時不連續將該鍵注冊為擊鍵,請將 e.SuppressKeyPress 包裝在 class 級別變量中,該變量在按住鍵時進行注冊。

public class nonRepeatingTextBox : TextBox
{
    private bool keyDown = false;

    protected override void OnKeyUp(KeyEventArgs e)
    {
        keyDown = false;
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (keyDown)
        {
            e.SuppressKeyPress = true;
        }
        keyDown = true;
    }
}

將此 class 用作您的文本框。 您可能希望在 OnKeyDown 覆蓋中為箭頭鍵等設置例外。

我意識到我玩游戲遲到了,但我需要 vb 中的這個功能,並認為我會分享我的經驗。

接受的答案似乎相當模糊,雖然它確實表達了答案的一部分,但我覺得它並沒有完全消除它。 Stuart Helwig 有一些有趣的代碼,但不幸的是它有一些相當大的缺點:1)如果你打字太快以至於在敲下一個鍵之前你還沒有釋放上一個鍵,它被排除在外 2)KeyDown 適用於 shift , alt 和 control 鍵以及沒有 CAPSLOCK 的大寫字母。 因此,這是我試圖清除答案的嘗試。 我希望有人發現它很有用,因為這是我的 RegexTextBox 急需的功能,它具有可以通過按住一個鍵來繞過的限制功能。

像 Stuart Helwig 一樣,我繼承了 TextBox 控件並添加了以下 Subs。

我正在使用KeyDownKeyPressKeyUp事件來解決問題。 KeyDown事件將KeyCode記錄到KeyPressed字段以供以后比較, KeyPress評估Keychar (但不是 shift、alt、control)並使用KeyPressEventArgs.Handled刪除 char 條目,而KeyUp重置keyPressedKeyIsDown字段。

Private Sub PreventHoldKeyUp(sender As Object, e As KeyEventArgs) _
        Handles Me.KeyUp
        Me.KeyIsDown = False
        Me.KeyPressed = Keys.None
End Sub

Private Sub PreventHoldKeyDown(sender As Object, e As KeyEventArgs) _
         Handles Me.KeyDown
        /* Recording the current key that was hit for later comparison */
        Me.KeyPressed = e.KeyCode
End Sub

Private Sub PreventKeyPressHold(sender As Object, e As KeyPressEventArgs) _
        Handles Me.KeyPress
        /* If a key has been struck and is still down */
        If Me.KeyIsDown Then

            /* The following allows backspace which is picked up by
             keypress but does not have a keychar */
            Select Case Convert.ToInt32(e.KeyChar)
                Case Keys.Back
                    Exit Sub
            End Select
            /* If this is the same key picked up by keydown abort */
            /* this portion allows fast typing without char drop
             but also aborts multiple characters with one key press */
            If Me.KeyPressed = Convert.ToInt32(e.KeyChar) Then
                e.Handled = True
            End If
        Else
            e.Handled = False
        End If

        Me.KeyIsDown = True

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM