No, it's not possible to differentiate between left and right Shift, Ctrl, and Alt keys with the .NET Framework SendKeys.Send(String) method, but you're on the right track with the Keys
enum. You'll need to use interop services instead.
Since the method you are inquiring about is in the namespace System.Windows.Forms
, I've assumed you're working with WinForms. Below are partial instructions for creating a WinForms app that has six buttons which send Right Shift, Left Shift, Right Alt, Left Alt, Right Ctrl, and Left Ctrl keys to the app's own window. Put a Label on the Form so that it can display whichever of the six keys was pressed. This is made possible by overriding DefWndProc.
你应该能够填补缺失的部分。更改应用程序以将这些击键发送到另一个应用程序也不应该太困难。
确保 Form1.cs 文件顶部有这些 using 语句:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
在顶部的 Form1.cs 类中声明:
- 一个常量字段,表示您要发送的消息类型
- 用于存储应用程序窗口句柄的字段
- SendMessage Windows API 方法
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);
}