0

You can use SendKeys to send keystrokes to the focused control on the currently active application. This answer shows how to bring an application to the foreground so that it can be made the target of SendKeys.

But this assumes that there is a single window. Is there any way to use SendKeys with particular windows of the same application, or even to somehow close windows?

Community
  • 1
  • 1
Gigi
  • 28,163
  • 29
  • 106
  • 188
  • "particular windows of the same application" is a little bit ambiguous. Do you mean multiple processes of the same executable, or actually multiple forms (a.k.a. "windows") in the same process? – rory.ap Feb 10 '15 at 12:02
  • Same process, multiple windows. – Gigi Feb 10 '15 at 12:59

1 Answers1

1

You might be better off using UI Automation for this. I've provided some sample code below, which activates the first Firefox window having "Stack Overflow" in its caption. You can obviously test for any other condition available to the Automation API. I picked Firefox as a sample application because it still (as of v35) uses a single process for all its tabs and windows.

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

An advantage of UI Automation over SendKeys is that it allows you to find and manipulate specific controls using a managed API (rather than P/Invoke wizardry). For example, to update a textbox, you can use the ValuePattern.SetValue method.

Douglas
  • 53,759
  • 13
  • 140
  • 188