how to send Ctrl + G to another application?

458 views Asked by At

I'm trying to send CTRL + G keys using InputSimulator with ForegroundWindow but it doesn't work. With other keys it works as expected, for example Ctrl + A or Ctrl + C

hotkeys menu options

I have tried with:

Process[] p = Process.GetProcessesByName("notepad");
if (p != null && p.Length > 0)
{
    IntPtr h = p[0].MainWindowHandle;
    SetForegroundWindow(h);
    InputSimulator sim = new InputSimulator();
    sim.Keyboard.ModifiedKeyStroke (VirtualKeyCode.CONTROL, VirtualKeyCode.VK_G) .Sleep (300);
 }

or

 Process[] p = Process.GetProcessesByName("notepad");
 if (p != null && p.Length > 0)
 {
    IntPtr h = p[0].MainWindowHandle;
    SetForegroundWindow(h);
    InputSimulator sim = new InputSimulator();
    sim.Keyboard.KeyDown(VirtualKeyCode.CONTROL);
    sim.Keyboard.KeyPress(VirtualKeyCode.VK_G).Sleep(300);
    sim.Keyboard.KeyUp(VirtualKeyCode.CONTROL).Sleep(300);
}

Also try:

SendKeys.Send ("^ (g)");

I have even tried keybd_event (user32.dll function)

1

There are 1 answers

1
RyanHx On

You need to force the other window into focus before sending the keystrokes. The Microsoft docs have examples detailing this process - link

In short, they use FindWindow followed by SetForegroundWindow, then send the keys via SendKeys.SendWait(), though you can optionally use SendKeys.Send()

This answer seems like a concise implementation of the FindWindow + SetForegroundWindow process.