How to simulate a Ctrl A + Ctrl C using keybd_event

35,624

This should work

[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

public const int KEYEVENTF_KEYDOWN = 0x0000; // New definition
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 A = 0x41; //A key code
public const int C = 0x43; //C key code

public static void PressKeys()
{
    // Hold Control down and press A
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYDOWN, 0);
    keybd_event(A, 0, KEYEVENTF_KEYDOWN, 0);
    keybd_event(A, 0, KEYEVENTF_KEYUP, 0);
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);

    // Hold Control down and press C
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYDOWN, 0);
    keybd_event(C, 0, KEYEVENTF_KEYDOWN, 0);
    keybd_event(C, 0, KEYEVENTF_KEYUP, 0);
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);
}
Share:
35,624

Related videos on Youtube

jith10
Author by

jith10

Updated on November 14, 2020

Comments

  • jith10
    jith10 over 3 years

    How to simulate a Ctrl-A + Ctrl-C using keybd_event?

    Because I am simulating a ctrl a + ctrl c on a webbrowser form to copy the entire contents on clipboard. i used the SendKeys.SendWait but it is not copying the entire contents!

    • default
      default over 11 years
      what is it that you actually want to do?
  • jith10
    jith10 over 11 years
    Hi Bali thanks a lot for your post. I guess in any other case this would have worked. But in my case the browser control is only considering the first logical ‘grouping’ of html… maybe its hitting the next ‘anchor’ and that is causing it not to copy all...!!! Got to look in depth.. thanks a ton!! I will keep this post updated as and when i get a solution...
  • GravityWell
    GravityWell over 9 years
    Note that KEYEVENTF_EXTENDEDKEY is not key down. There is no define for key down. Use 0 (or make your own define).
  • Gerard
    Gerard over 4 years
    keybd_event(C, 0, 0, 0); keybd_event(C, 0, 2, 0); works for me.