您在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 而不是小写字母。因此,解决方案很明显:您需要找到一种方法来取消该按键,以便操作系统不会对其进行处理。当然,如果您吃掉了按键事件,您还需要想办法跟踪它,以便您的应用程序仍然知道它何时被按下并可以采取相应的行动。BSendInput
Shift
快速搜索显示已经询问并回答了有关密钥的类似问题。
特别是,您需要编写处理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;
}
}