繁体   English   中英

C# - 如何使用SendKeys.Send使用SHIFT键发送小写字母?

[英]C# - How to send small letters with SHIFT key using SendKeys.Send?

我正在为我的项目使用这个键盘钩子。 我无法使用SendKeys.Send()按下SHIFT修改键来发送小写字母。 我的应用程序需要(例如)如果用户按下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.SupressKeyPressSendKeys(“b”.toLower())并将上面的代码放在KeyUp事件中但是静脉。

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

您在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键,您需要使用全局钩子来完成此操作。

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

快速搜索显示一个类似的问题已经被问及并回答了关于 Windows徽标 键。

特别是,您需要编写处理由此类全局钩子引发的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;
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM