您在 Shift 键仍然按下时发送键,这导致它们变为大写。
您需要找到一种方法来取消 Shift 按键以及 K 按键。
您使用的全局钩子示例有点简单;它应该也报告哪些修饰键被按住。不幸的是,该功能似乎尚未实现。
为什么首先需要使用键盘挂钩?您真的需要处理表单没有焦点时发生的关键事件吗?如果是这样,你到底为什么要使用SendKey?您如何知道当前活动的应用程序将如何处理您发送的按键操作?
这看起来可以更好地处理表单的ProcessCmdKey method,而不是。例如:
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 键按下,以便操作系统不会对其进行处理。当然,如果你吃掉了按键事件,你还需要想办法跟踪它,这样你的应用程序仍然知道它什么时候被按下并可以做出相应的反应。
快速搜索发现a similar question 已经被询问并回答了关于 键的问题。
特别是,您需要编写代码来处理由全局钩子引发的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;
}
}