简体   繁体   English

禁用文本框中的某些键盘操作。 (VC# Windows 窗体应用程序)

[英]Disable certain keyboard actions in TextBoxes. (VC# Windows Form Application)

I'm making a game with TextBox es but they can cheat if they use ctrl + a or ctrl + z .我正在使用TextBox es 制作游戏,但如果他们使用ctrl + actrl + z他们可能会作弊。 How do I make those actions enabled within my textBoxes?如何在我的文本框中启用这些操作?

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;
    }
}

KeyDown event occurs when a key is first pressed. KeyDown事件在第一次按下某个键时发生。 Instead, Use KeyPress event which occurs when a control has focus and the user presses and releases a key.相反,使用KeyPress事件,当控件具有焦点并且用户按下并释放某个键时会发生该事件。 KeyPress event has KeyPressEventArgs . KeyPress事件具有KeyPressEventArgs SO you will have to use e.handled = true instead of e.SuppressKeyPress event.所以你将不得不使用e.handled = true而不是e.SuppressKeyPress事件。

For using Keyboard class and Key enum, you have to add PresentationCore and WindowsBase assemblies to your project references.要使用Keyboard类和Key枚举,您必须将PresentationCoreWindowsBase程序集添加到您的项目引用中。

KeyPress event: KeyPress事件:

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;
        }
    }
}

I trust this helps you with your problem.我相信这可以帮助您解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM