Trying to reproduce keystrokes. Everywhere I stumble on SendKeys. Why do I need to pass a string when there is KeyDown, KeyPress, KeyUp for reading the keyboard? Is there an alternative to SendKeys, which accepts Keys as input and the type of event?

    2 answers 2

    KeyDown and the rest next to it are events that are triggered when receiving keyboard input data. And SendKeys needs to simulate this very keyboard input.

    You can call your KeyDown handler manually, but by doing so you will deceive only that part of the program that depends on this handler. And the rest of the program, which handles keystrokes differently, will still assume that no keys were pressed.

    • Thanks, but the question is a little different - is there an analogue of SendKeys, where for emulation I can not transfer strings, but the same Keys. In my opinion, it is somehow illogical - you have to convert the saved Keys (I try to repeat the user's actions in the program) into the string while taking into account both Shift and Ctrl, etc. Or, for example, I will try to emulate dragging with the mouse while pressing Control (i.e. pass that Ctrl is held for some time). How is this implemented with SendKeys? - kvvk
    • @kvvk: I'm afraid that's impossible. Now I will try to find proofs. - VladD
    • @kvvk: You can theoretically use SendInput , but SendKeys under the hood does the same. - VladD
    • The result is also a result, I will know. Thanks for the links, useful! - kvvk
    • @kvvk: Please! Hope it helped anyway. - VladD

    I found the answer all the same: keybd_event - MSDN

    as a result I do this:

     public static class keyImitation { [DllImport("user32.dll", SetLastError = true)] private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo); public static void KeyDown(Keys key) { keybd_event((byte)key, 0, 0, 0); } public static void KeyUp(Keys key) { keybd_event((byte)key, 0, 0x2, 0); } } 
    • But after all in MSDN it is written that instead of keybd_event you need to use SendInput ? That is, if something works with keybd_event , it should work with SendInput on the idea. - VladD
    • @VladD I confess, I lost my temper, but did not understand the INPUT structure. And keybd_event was easily read and entered into the code. Yes, I took the easy way ... - kvvk
    • one
      On the other hand, do we have a collection of practical knowledge here? It works - it means it counts as a decision. - VladD