首页 > 解决方案 > 如何将 Ctrl + G 发送到另一个应用程序?

问题描述

我正在尝试使用带有 ForegroundWindow 的 InputSimulator 发送 CTRL + G 键,但它不起作用。使用其他键,它可以按预期工作,例如 Ctrl + A 或 Ctrl + C

热键菜单选项

我尝试过:

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);
 }

或者

 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);
}

也试试:

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

我什至尝试过 keybd_event (user32.dll 函数)

标签: c#keyboard-shortcutssendkeysctrlinputsimulator

解决方案


在发送击键之前,您需要强制另一个窗口成为焦点。Microsoft 文档有详细说明此过程的示例 -链接

简而言之,他们使用FindWindow后跟SetForegroundWindow,然后通过 发送密钥SendKeys.SendWait(),尽管您可以选择使用SendKeys.Send()

这个答案似乎是FindWindow+SetForegroundWindow过程的简洁实现。


推荐阅读