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.