在 C# 中使用 SetForegroundWindow 和 SendKeys 激活 Window 和发送输入

Activate Window and Send Input using SetForegroundWindow and SendKeys in C#

我想做的是激活另一个应用程序并向其发送键输入以触发按钮。但是这段代码似乎不起作用。看起来它可以找到应用程序,但没有激活它,也没有发送密钥。

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);

private void debugButton_Click(object sender, EventArgs e)
    {
        //GetProcess by Class
        IntPtr rightNowHandle = FindWindow("WindowsForms10.Window.8.app.0.24dc298_r17_ad2", null);
        //Get Handle by Process
        Process proc = Process.GetProcessesByName("RightNow.CX")[0];
        IntPtr ptrFF = proc.MainWindowHandle;
        //Get a handle for the Calculator Application main window
        if (rightNowHandle == IntPtr.Zero)
        {
           MessageBox.Show("Could Not Find Right Now");
            return;
        }
        SetForegroundWindow(rightNowHandle); //Activate Handle By Class
        //SetForegroundWindow(ptrFF); //Activate Handle By Process
        SendKeys.SendWait("{F1}");
    }

这是我用 Window Spy

拉的东西

如有任何帮助,我们将不胜感激。谢谢

解决了我的问题。

SetForegroundWindow 应用程序在最小化时不显示,这正是我所期待的。

接下来我使用 Windows Input Simulator 来发送输入而不是 SendKeys。

这是我最终使用的代码。

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
    private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);
private const int SW_RESTORE = 9;

private void debugButton_Click(object sender, EventArgs e)
    {
        //GetProcess by Class
        IntPtr rightNowHandle = FindWindow("WindowsForms10.Window.8.app.0.24dc298_r17_ad2", null);
        //Get Handle by Process
        Process proc = Process.GetProcessesByName("RightNow.CX")[0];
        IntPtr ptrFF = proc.MainWindowHandle;
        //Get a handle for the Calculator Application main window
        if (rightNowHandle == IntPtr.Zero)
        {
           MessageBox.Show("Could Not Find Right Now");
            return;
        }
        SetForegroundWindow(ptrFF); //Activate Handle By Process
        ShowWindow(ptrFF, SW_RESTORE); //Maximizes Window in case it was minimized.
        //SetForegroundWindow(rightNowHandle); //Activate Handle By Class
        InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.LMENU, VirtualKeyCode.VK_A); //Send Left Alt + A
    }