ePa*_*dit 5 .net c# keyboard-hook sendkeys
我在我的项目中使用这个键盘钩子。我无法在按下 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;
}
Run Code Online (Sandbox Code Playgroud)
但它发送的是“B”(大写字母)而不是“b”,即该SHIFT键将发送的击键“b”更改为大写。即使将Keys.Shift添加到挂钩后也会发生这种情况。
我尝试了很多方法,包括使用e.SupressKeyPress、SendKeys("b".toLower())并将上面的代码放在 KeyUp 事件中,但本质上是这样。
请帮助我,我非常沮丧,我的应用程序开发此时受到了打击。
您在按键仍处于按下状态时发送按键Shift,这导致它们变成大写。
你需要想办法Shift在按键的同时取消按键K。
您使用的全局钩子示例有点简单;它还应该报告哪些修饰键被按下。不幸的是,该功能似乎尚未实现。
为什么首先需要使用键盘挂钩?您真的需要处理表单没有焦点时发生的关键事件吗?如果是这样,你到底为什么要使用SendKey?您如何知道当前活动的应用程序将如何处理您发送的按键?
这看起来像是通过重写表单的ProcessCmdKeymethod来更好地处理。例如:
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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:您的评论表明您实际上需要处理当您没有焦点时发生的关键事件。假设您需要处理的不仅仅是K密钥,您将需要使用全局挂钩来完成此操作。
Shift正如我之前提到的,问题在于,当您使用 发送密钥时,B用户仍然按住该键SendInput,这导致它注册为大写字母 B 而不是小写字母。那么解决方案就很明显了:您需要找到一种方法来取消该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;
}
}
Run Code Online (Sandbox Code Playgroud)