繁体   English   中英

模拟ctrl键向下事件和ctrl键向上事件后,Ctrl键保持按下状态

[英]Ctrl key kept down after simulating a ctrl key down event and ctrl key up event

我有一个小程序,使用系统keybd_event模拟ctr + cctr + v (复制和粘贴)事件。 问题是,该程序运行后计算机继续,如同Ctrl键被按下时采取行动,然后-如果我键入它选择整个文档,如果我滚动鼠标滚轮它改变了文字的一面,等它发生不仅在Visual Studio编辑器中,而且在程序以Word等运行时打开的任何其他程序。这是我的代码:

    //The system keyboard event.
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

    public const int KEYEVENTF_EXTENDEDKEY = 0x0001; //Key down flag
    public const int KEYEVENTF_KEYUP = 0x0002; //Key up flag
    public const int VK_LCONTROL = 0xA2; //Left Control key code
    public const int C = 0x43; // C key code
    public const int V = 0x56; // V key code

    static void Main(string[] args)
    {
        Thread.Sleep(1000);// So I have time to select something.

        //Simulate ctrl+c
        keybd_event(VK_LCONTROL, 0, KEYEVENTF_EXTENDEDKEY, 0);
        keybd_event(C, 0, KEYEVENTF_EXTENDEDKEY, 0);
        keybd_event(C, 0, KEYEVENTF_KEYUP, 0);
        keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);

        //Simulate ctrl+v
        keybd_event(VK_LCONTROL, 0, KEYEVENTF_EXTENDEDKEY, 0);
        keybd_event(V, 0, KEYEVENTF_EXTENDEDKEY, 0);
        keybd_event(V, 0, KEYEVENTF_KEYUP, 0);
        keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);
    }

有人知道我能做些什么来解决这个问题吗?

这是解决方案,这完全适合我。 请注意参数中的更改发送到keybd_event。 我使用了CodeProject的一篇文章,链接: http//www.codeproject.com/Articles/7305/Keyboard-Events-Simulation-using-keybd-event-funct 这是我修复过的代码:

    //The system keyboard event.
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
    public const int KEYEVENTF_KEYUP = 0x0002; //Key up flag
    public const int VK_CONTROL = 0x11; //Control key code
    public const int C = 0x43; // C key code
    public const int V = 0x56; // V key code

    static void Main(string[] args)
    {
        Thread.Sleep(1000);// So I have time to select something.

        // Simulating Ctrl+C
        keybd_event(VK_CONTROL, 0x9d, 0, 0); // Ctrl Press
        keybd_event(C, 0x9e, 0, 0); // ‘A’ Press
        keybd_event(C, 0x9e, KEYEVENTF_KEYUP, 0); // ‘A’ Release
        keybd_event(VK_CONTROL, 0x9d, KEYEVENTF_KEYUP, 0); // Ctrl Release

        // Simulating Ctrl+V
        keybd_event(VK_CONTROL, 0x9d, 0, 0); // Ctrl Press
        keybd_event(V, 0x9e, 0, 0); // ‘A’ Press
        keybd_event(V, 0x9e, KEYEVENTF_KEYUP, 0); // ‘A’ Release
        keybd_event(VK_CONTROL, 0x9d, KEYEVENTF_KEYUP, 0); // Ctrl Release
   }

我希望这会对某人有所帮助。 感谢所有帮助过我的人!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM