以编程方式按下“右 Shift”键

6

我在寻找一种编程方式,能够按下右 shift 键。我需要实现单个键的按下和释放操作。

我目前所拥有的代码如下:

SendKeys.Send("{RSHIFT}")

我知道Shift键的作用是:

SendKeys.Send("+")

我猜是指Shift键,但我需要的是右Shift键。

能否有人帮我解决下这段代码?


2
我在 SendKeys.Send 中没有看到任何 {RSHIFT},而且根据我所了解的,它也没有办法识别左右 shift 键。 - Steve
2
是的!这就是我发布这个问题的原因,为了发现如何完成任务。 - Eduards
1
也许有不同的方法来完成你的任务。为什么需要发送右移键?你是在尝试与另一个应用程序通信吗? - Steve
2
是的,它需要特定的“右移键”。 - Eduards
1
我已更新之前的答案,请查看新答案。 - AliReza Sabouri
2个回答

6
使用 keybd_event 函数时,不需要窗口句柄。
VB 代码:
Public Class MyKeyPress
    <DllImport("user32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)>
    Public Shared Sub keybd_event(ByVal bVk As UInteger, ByVal bScan As UInteger, ByVal dwFlags As UInteger, ByVal dwExtraInfo As UInteger)
    End Sub


    ' To find other keycodes check bellow link
    ' http://www.kbdedit.com/manual/low_level_vk_list.html
    Public Shared Sub Send(key As Keys)
        Select Case key
            Case Keys.A
                keybd_event(&H41, 0, 0, 0)
            Case Keys.Left
                keybd_event(&H25, 0, 0, 0)
            Case Keys.LShiftKey
                keybd_event(&HA0, 0, 0, 0)
            Case Keys.RShiftKey
                keybd_event(&HA1, 0, 0, 0)
            Case Else
                Throw New NotImplementedException()
        End Select
    End Sub
End Class

C#:

public static class MyKeyPress
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern void keybd_event(uint bVk, uint bScan, uint dwFlags, uint dwExtraInfo);


    // To get other key codes check bellow link
    // http://www.kbdedit.com/manual/low_level_vk_list.html
    public static void Send(Keys key)
    {
        switch (key)
        {
            case Keys.A:
                keybd_event(0x41, 0, 0, 0);
                break;
            case Keys.Left:
                keybd_event(0x25, 0, 0, 0);
                break;
            case Keys.LShiftKey:
                keybd_event(0xA0, 0, 0, 0);
                break;
            case Keys.RShiftKey:
                keybd_event(0xA1, 0, 0, 0);
                break;
            default: throw new NotImplementedException();
        }
    }
}

使用方法:

MyKeyPress.Send(Keys.LShiftKey)

5

通过创造性的关键词组合找到此内容

发送按键码的关键在于以下代码:

Keys key = Keys.RShiftKey;//Right shift key  
SendMessage(Process.GetCurrentProcess().MainWindowHandle, WM_KEYDOWN, (int)key, 1);

我不知道这里的使用场景是什么,但要注意传递的窗口句柄参数:Process.GetCurrentProcess().MainWindowHandle

这会将按键发送给自身。如果您想把它发送到另一个进程/程序,您需要传递该程序的窗口句柄。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接