我正在尝试使用e.KeyData,但它返回“NumPad2”或“D2”我希望只返回“2”,可以使用e.keycode或其他..因为它工作,我已经尝试转换为int没有任何作用。
答案 0 :(得分:2)
这应该让你开始。
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
string pressedKey = e.KeyData.ToString();
if (pressedKey.StartsWith("D"))
{
pressedKey = pressedKey.Replace("D", "");
MessageBox.Show(pressedKey);
}
if (pressedKey.StartsWith("NumPad"))
{
pressedKey = pressedKey.Replace("NumPad", "");
MessageBox.Show(pressedKey);
}
}
答案 1 :(得分:0)
经过一些研究,看来你要么做一些类似于Rikki B建议的事情,要么你可以创建一个自定义文本框并覆盖OnKeyDown和OnKeyPress,如下所示:
首先创建自定义事件参数:
public class CustomKeyEventArgs : KeyEventArgs
{
public char LastCharPressed { get; set; }
public CustomKeyEventArgs(Keys keyData, char lastCharPressed) : base(keyData)
{
LastCharPressed = lastCharPressed;
}
}
然后在自定义文本框中进行设置:
public delegate void CustomKeyUpHandler(object sender, CustomKeyEventArgs e);
public event CustomKeyUpHandler OnCustomKeyUp;
private char lastChar;
protected override void OnKeyPress(KeyPressEventArgs e)
{
lastChar = e.KeyChar;
base.OnKeyPress(e);
}
protected override void OnKeyUp(KeyEventArgs e)
{
if(OnCustomKeyUp != null)
OnCustomKeyUp(this, new CustomKeyEventArgs(e.KeyData, lastChar));
base.OnKeyUp(e);
}