SetForegroundWindow
Set a window into the foreground and activate the automation control.
void SetForegroundWindow();
Parameters
None
Remarks
For some windows this action may result in the icon in the taskbar flashing to indicate use attention is required rather than putting the window at the top of the Z-order. To put a top level window into the foreground use ShowWindow. To set focus for an automation control use AutomationControl.Element.Setfocus().
Often the most reliable way to ensure a window is in focus is to perform a Left mouse click on a area such as the title bar.
Example
AutomationControl notepadWindow = FindTopAutomationWindow("Untitled - Notepad"); // find the top level window
notepadWindow.SetForegroundWindow(); // this will ensure the window is in the foreground and activated
notepadWindow.Element.setFocus(); // set the focus using the automation element
notepadWindow.LeftClickLHS(100, 5); // set focus by clicking on the title bar
// The example below demonstrates how multiple windows are treat with SetForegroundWindow() method.
IList<AutomationControl> notepadWindows = FindTopAutomationWindows("Notepad", TextMatch.EndsWith); //finds all active notepad windows
if(notepadWindows.Count == 0)
{
WriteMessage("Couldn't to find any windows open with indicated name");
}
else
{
for (int windowNumber = 0; windowNumber < notepadWindows.Count; windowNumber++)
{
notepadWindows[windowNumber].SetForegroundWindow();//this will ensure the window is in the foreground and activated
SendKeys("Window number: " + (windowNumber + 1)); //type window number on each open window
}
}
Related: