The Ctrl key is held after simulating the ctrl key down and ctrl key up events

I have a small program that simulates the events ctr + c and ctr + v (copy and paste) using the keybd_event system. The problem is that after starting the program, the computer continues to act as if the ctrl key is pressed, and then - if I type a , it selects the entire document, if I roll the mouse wheel, it changes the text side, etc. This happens not only in the Visual Studio editor, but also in any other program that was open when the program was executed as Word, etc. Here is my code:

  //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); } 

Does anyone know what I can do to solve this problem?

+6
source share
1 answer

Here is the solution, it worked for me completely. Notice the change in send options on keybd_event. I used the CodeProject article, link: http://www.codeproject.com/Articles/7305/Keyboard-Events-Simulation-using-keybd-event-funct . This is my recovered code:

  //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 } 

Hope this helps someone. Thanks to everyone who helped me!

+4
source

Source: https://habr.com/ru/post/980216/


All Articles