[英]How to detect a custom key from Keyboard using C#
I have a USB Keyboard that have some Special keys like "FN",PLAY,MUTE and one that changes the keyboard light. 我有一个USB键盘,其中有一些特殊键,例如“ FN”,PLAY,MUTE和一个可以改变键盘灯的键。 I was trying to get what is this key "name" to perform a logic to change the color periodically.
我试图获取这个键的“名称”是什么,以执行逻辑以定期更改颜色。
private void textBox1_TextChanged(object sender, EventArgs e)
{
var key = sender as TextBox;
var result = key.Text;
}
But the key its not a string to be recognized. 但是密钥不是一个可以识别的字符串。 How can I do this ?
我怎样才能做到这一点 ? Thanks!
谢谢!
I will suggest you to use OnKeyPress
and OnKeyDown
events instead to check what was pressed. 我建议您使用
OnKeyPress
和OnKeyDown
事件来检查按下的内容。 MSDN Link . MSDN链接 。
Example: 例:
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
//If shift key was pressed, it's not a number.
if (Control.ModifierKeys == Keys.Shift) {
nonNumberEntered = true;
}
}
// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.