I’m working on a program to trigger cut and pastes
Pastes I have no problem with (I just dump a string into the clipboard)
Cut and or Copys are proving to be a little more difficult
The program I have is out of focus and has several hot keys registered with the os CTRL+ALT+2 CTRL+ALT+3 etc)
That I want to use to trigger Windows to copy anything that is highlighted in the window that is focused
I tried doing a sendkeys
SendKeys.Send("^c");
but that seems to work once or twice if at all then stop working.
is there a better way to try to trigger windows into coping highlighted content on a different window
One way to do this is by using the Win32
SendInputfunction. WithSendInput, you have to simulate both the key down and key up events in order for the full key press to register. To simulate CTRL+C, you’d have to do:pinvoke.net has some examples of
SendInputusage. One issue to be mindful of is if the key is already pressed. You can useGetAsyncKeyStateto only simulate a key down event if the key is not already down.Below is some example code of how you could simulate CTRL+C. With the code below, you can simply call
Keyboard.SimulateKeyStroke('c', ctrl: true);Note that this works as if the user literally pressed CTRL+C, so the active application will behave as it always does when such an event happens (i.e. if nothing is normally copied, then nothing will be copied with this method, either).Edit: See David’s comment below about batching the sent input. The code below should be sending the entire sequence of input events through a single call to
SendInputto avoid being interleaved (and misinterpreted) with real user input events.