[英]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 + a
或ctrl + 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 andKey
enum, you have to addPresentationCore
andWindowsBase
assemblies to your project references.要使用Keyboard
类和Key
枚举,您必须将PresentationCore
和WindowsBase
程序集添加到您的项目引用中。
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.