5

我正在为我的项目使用这个键盘挂钩。我无法在按下 SHIFT 修饰键的情况下使用 SendKeys.Send() 发送小写字母。我的应用程序需要(例如)如果用户按下K按钮“a”应该发送,如果他按下SHIFT+ K“b”应该被发送。代码是:

void gkh_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.K)
    {
        if (Control.ModifierKeys == Keys.Shift)
            SendKeys.Send("b");
        else
            SendKeys.Send("a");
    }
    e.Handled == true;   
}

但它发送"B"(大写字母)而不是"b",即SHIFT键将发送的击键“b”更改为大写。即使在将Keys.Shift添加到钩子之后也会发生这种情况。

我尝试了很多方法,包括使用e.SupressKeyPress SendKeys("b".toLower())并将上面的代码放在 KeyUp 事件中,但在静脉中。

请帮助我,我很沮丧,我的应用程序开发在这一点上受到打击。

4

1 回答 1

4

您在Shift密钥仍处于关闭状态时发送密钥,这导致它们被大写。
您需要想出一种方法来取消Shift按键以及K按键。

您正在使用的全局钩子示例有点裸露;它还应该报告按下了哪些修饰键。不幸的是,该功能似乎尚未实现。

为什么首先需要使用键盘挂钩?你真的需要处理表单没有焦点时发生的关键事件吗?如果是这样,你到底为什么要使用SendKey?您如何知道当前活动的应用程序将如何处理您发送的按键操作?

ProcessCmdKey这看起来像是在覆盖表单的方法时会更好地处理的事情,而不是。例如:

  protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
  {
     if (keyData == (Keys.K | Keys.Shift))
     {
        SendKeys.Send("b");
        return true;  // indicate that you handled the key
     }
     else if (keyData == Keys.K)
     {
        SendKeys.Send("a");
        return true;  // indicate that you handled the key
     }

     // call the base class to handle the key
     return base.ProcessCmdKey(ref msg, keyData);
  }

编辑:您的评论表明您确实需要处理当您形成没有焦点时发生的关键事件。假设您需要处理的不仅仅是K密钥,您将需要使用全局挂钩来执行此操作。

正如我之前提到的,问题是用户在使用Shift发送密钥时仍然按住键,这导致它注册为大写字母 B 而不是小写字母。因此,解决方案很明显:您需要找到一种方法来取消该按键,以便操作系统不会对其进行处理。当然,如果您吃掉了按键事件,您还需要想办法跟踪它,以便您的应用程序仍然知道它何时被按下并可以采取相应的行动。BSendInputShift

快速搜索显示已经询问并回答了有关密钥的类似问题。Windows logo

特别是,您需要编写处理KeyDown由全局挂钩引发的事件的代码(至少,此代码适用于我编写的全局挂钩类;它也应该适用于您的,但实际上我没有测试它):

// Private flag to hold the state of the Shift key even though we eat it
private bool _shiftPressed = false;

private void gkh_KeyDown(object sender, KeyEventArgs e)
{
   // See if the user has pressed the Shift key
   // (the global hook detects individual keys, so we need to check both)
   if ((e.KeyCode == Keys.LShiftKey) || (e.KeyCode == Keys.RShiftKey))
   {
      // Set the flag
      _shiftPressed = true;

      // Eat this key event
      // (to prevent it from being processed by the OS)
      e.Handled = true;
   }


   // See if the user has pressed the K key
   if (e.KeyCode == Keys.K)
   {
      // See if they pressed the Shift key by checking our flag
      if (_shiftPressed)
      {
         // Clear the flag
         _shiftPressed = false;

         // Send a lowercase letter B
         SendKeys.Send("b");
      }
      else
      {
         // Shift was not pressed, so send a lowercase letter A
         SendKeys.Send("a");
      }

      // Eat this key event
      e.Handled = true;
   }
}
于 2011-03-26T15:26:24.237 回答