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
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)
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
FindWindowfollowed bySetForegroundWindow, then send the keys viaSendKeys.SendWait(), though you can optionally useSendKeys.Send()This answer seems like a concise implementation of the
FindWindow+SetForegroundWindowprocess.