在文本框中禁用某些键盘动作.(vc# Windows窗体应用程序)

本文关键字:vc# Windows 窗体 应用程序 键盘 文本 | 更新日期: 2023-09-27 18:14:43

我正在制作一款使用TextBox的游戏,但如果他们使用ctrl + actrl + z,他们可能会作弊。如何在文本框中启用这些操作?

I tried doing this:

private void Form1_Load(object sender, EventArgs e)
{
    foreach (Control x in this.Controls)
    {
        if (x is TextBox)
        {
            ((TextBox)x).KeyDown += textBox_KeyDown;
        }
    }          
}
static void textBox_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode == Keys.Z && e.KeyCode == Keys.ControlKey)
    {
        e.SuppressKeyPress = true; 
    }
    if (e.KeyCode == Keys.A && e.KeyCode == Keys.ControlKey)
    {
        e.SuppressKeyPress = true;
    }
}

在文本框中禁用某些键盘动作.(vc# Windows窗体应用程序)

首次按下键时发生KeyDown事件。相反,使用KeyPress事件,当控件有焦点并且用户按下和释放键时发生。KeyPress事件有KeyPressEventArgs。因此,您将不得不使用e.handled = true而不是e.SuppressKeyPress事件。

要使用Keyboard类和Key enum,您必须将PresentationCoreWindowsBase程序集添加到您的项目引用中。

KeyPress event:

static void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
    {
        if (Keyboard.IsKeyDown(Key.A))
        {
            e.Handled = true;
        }
        if(Keyboard.IsKeyDown(Key.Z))
        {
            e.Handled = true;
        }
    }
}

我相信这对你的问题有帮助。