我主要研究了几个选项;
但我无法找到是否可以将系统密钥的右侧或左侧变体发送到SendKey.Send()
api。例如,可以通过按照"+A"
提供documentation来发送通用shift + A,但我需要能够区分左右移位,控制和alt等。
甚至可能与SendKeys.Send()
?
除此之外,我想知道是否有使用类似Keys枚举的解决方案。
不可以,使用.NET Framework SendKeys.Send(String)方法区分左右Shift,Ctrl和Alt键是不可能的,但是你使用Keys
枚举是在正确的轨道上。您需要使用互操作服务。
由于您要查询的方法位于命名空间System.Windows.Forms
中,我假设您正在使用WinForms。以下是创建WinForms应用程序的部分说明,该应用程序有六个按钮,可将Right Shift,Left Shift,Right Alt,Left Alt,Right Ctrl和Left Ctrl键发送到应用程序自己的窗口。在表单上放置一个标签,以便它可以显示按下的六个键中的任何一个。通过重写DefWndProc可以实现这一点。
你应该能够填补缺失的部分。更改应用程序以将这些击键发送到另一个应用程序也不应该太难。
确保在Form1.cs文件的顶部有这些using语句:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
在顶部的Form1.cs类中声明:
const int WM_KEYDOWN = 0x100;
IntPtr _hWnd;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
在对InitializeComponent的调用下面的Form1构造函数中,定义一个事件处理程序,它允许您检索和存储应用程序的窗口句柄:
HandleCreated += new EventHandler((sender, e) =>
{
_hWnd = this.Handle;
});
将所有按钮指向同一个单击事件处理程序,每个按钮都相应地命名:
void button_Click(object sender, EventArgs e)
{
var button = (Button)sender;
var wParam = new IntPtr();
switch (button.Name)
{
case "buttonSendRightShift":
wParam = (IntPtr)Keys.RShiftKey;
break;
case "buttonSendLeftShift":
wParam = (IntPtr)Keys.LShiftKey;
break;
case "buttonSendRightAlt":
wParam = (IntPtr)Keys.RMenu;
break;
case "buttonSendLeftAlt":
wParam = (IntPtr)Keys.LMenu;
break;
case "buttonSendRightCtrl":
wParam = (IntPtr)Keys.RControlKey;
break;
case "buttonSendLeftCtrl":
wParam = (IntPtr)Keys.LControlKey;
break;
}
SendMessage(_hWnd, WM_KEYDOWN, wParam, 1);
}
像这样覆盖DefWndProc:
protected override void DefWndProc(ref Message m)
{
switch (m.Msg)
{
case WM_KEYDOWN:
switch ((Keys)m.WParam)
{
case Keys.RShiftKey:
LabelKeyPressed.Text = "Right Shift Key Received";
break;
case Keys.LShiftKey:
LabelKeyPressed.Text = "Left Shift Key Received";
break;
case Keys.RMenu:
LabelKeyPressed.Text = "Right Alt Key Received";
break;
case Keys.LMenu:
LabelKeyPressed.Text = "Left Alt Key Received";
break;
case Keys.RControlKey:
LabelKeyPressed.Text = "Right Ctrl Key Received";
break;
case Keys.LControlKey:
LabelKeyPressed.Text = "Left Ctrl Key Received";
break;
}
break;
}
base.DefWndProc(ref m);
}
我不知道SendKey.Send()
,但我知道替代解决方案。
使用AutoIt。它是一种用于自动化Windows GUI的脚本语言。重要的是它提供.dll
文件以允许.NET使用。您只需下载,安装它并添加对.dll
文件的引用。
您的代码将是这样的:AutoItX.Send("{RSHIFT}")