【问题标题】:Using SendKeys with multiple windows在多个窗口中使用 SendKeys
【发布时间】:2015-02-13 04:42:48
【问题描述】:

您可以使用SendKeys 将击键发送到当前活动应用程序上的焦点控件。 This answer 展示了如何将应用程序带到前台,使其成为 SendKeys 的目标。

但这假设只有一个窗口。有什么方法可以将 SendKeys 用于同一应用程序的特定窗口,甚至可以以某种方式关闭窗口?

【问题讨论】:

  • “同一应用程序的特定窗口”有点模棱两可。你的意思是同一个可执行文件的多个进程,还是同一个进程中的多个表单(又名“windows”)?
  • 同一个进程,多个窗口。

标签: winforms sendkeys


【解决方案1】:

为此,您最好使用UI Automation。我在下面提供了一些示例代码,它会激活第一个标题中带有“Stack Overflow”的 Firefox 窗口。您显然可以测试自动化 API 可用的任何其他条件。我选择 Firefox 作为示例应用程序,因为它仍然(从 v35 开始)对其所有选项卡和窗口使用单个进程。

// Get Firefox process.
var ffProcess = Process.GetProcessesByName("firefox").FirstOrDefault();
if (ffProcess != null)
{
    // Find all desktop windows belonging to Firefox process.
    var ffCondition = new PropertyCondition(AutomationElement.ProcessIdProperty, ffProcess.Id);
    var ffWindows = AutomationElement.RootElement.FindAll(TreeScope.Children, ffCondition);

    // Identify first Firefox window having "Stack Overflow" in its caption.
    var soWindow = ffWindows.Cast<AutomationElement>().FirstOrDefault(w => w.Current.Name.Contains("Stack Overflow"));
    if (soWindow != null)
    {
        // Treat automation element as a window.
        var soWindowPattern = soWindow.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern;
        if (soWindowPattern != null)
        {
            // Restore window (activating it).
            soWindowPattern.SetWindowVisualState(WindowVisualState.Normal);

            // Pause to observe effect. Do not set a breakpoint here.
            Thread.Sleep(4000);

            // Close window.
            soWindowPattern.Close();
        }
    }
}

SendKeys 相比,UI 自动化的一个优势是它允许您使用托管 API(而不是 P/Invoke 向导)查找和操作特定控件。例如,要更新文本框,可以使用ValuePattern.SetValue 方法。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多