WPF 获取键盘点击值、组合键方式

发布时间 2023-09-12 12:03:31作者: 潇潇烟雨

在xmal.cs文件中实现,或者重写OnPreviewKeyDown()方法:

string codeValue = "";

int InputCount = 0;
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
    int keyValue = Convert.ToInt32(e.Key);
    if (keyValue == 156)
    keyValue = Convert.ToInt32(e.SystemKey);
    if (e.Key == Key.Up)
    {
         e.Handled = true;
         ScrollToVerticalOffset("up");
    }
    if (e.Key == Key.Down)
    {
         e.Handled = true;
         ScrollToVerticalOffset("down");
    }

  
   //获取组合键,如Shift+F1【操作:按下Shift,同时按下F1】

    if (e.KeyStates == Keyboard.GetKeyStates(Key.F1) && Keyboard.Modifiers == ModifierKeys.Shift)
    {
      codeValue = "Shift+F1";

    }


  //获取数字组合键,如200,201等【操作:依次按2 0 0 】 if (e.Key.ToString().Contains("NumPad") || (keyValue >= 34 && keyValue <= 43)) { string keyCode = e.Key.ToString().Substring(e.Key.ToString().Length - 1, 1); if (int.TryParse(keyCode, out int tmp))//如果转换失败(为false)时输出括号内容 { codeValue += keyCode; InputCount += 1; } else { codeValue = ""; InputCount = 0; } if (Core.Definition.QuickKeyManager.Instance.Exec(this.GetType(), 0, codeValue)) { e.Handled = true; codeValue = ""; InputCount = 0; } if (InputCount == 3) { codeValue = ""; InputCount = 0; } return; } if (Core.Definition.QuickKeyManager.Instance.Exec(this.GetType(), keyValue)) e.Handled = true; codeValue = ""; InputCount = 0; base.OnPreviewKeyDown(e);
}