I have an application which on focus change should be able to retrieve the URL of the currently active tab if the opened program is a browser otherwise should just return the name of the program.
For example let say I have notepad opened in the foreground and then I alt-tab to my browser where I have 2 tabs opened I want the application to extract the URL of the active tab. The code below works to find the name of the tab but the code in the try catch which should be finding the URL of the tab doesn't work it just prints empty string.
I want to have the URL of the site so I can have a constant reference to it as the tab name could be different in the same site
private void OnFocusChangedHandler(object src, AutomationFocusChangedEventArgs args)
{
Debug.WriteLine("Focus changed!");
AutomationElement element = src as AutomationElement;
if (element != null)
{
string name = element.Current.Name;
string id = element.Current.AutomationId;
int processId = element.Current.ProcessId;
try
{
using (Process process = Process.GetProcessById(processId))
{
AutomationElement elm = AutomationElement.FromHandle(process.MainWindowHandle);
AutomationElement elmUrlBar = elm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
AutomationPattern[] patterns = elmUrlBar.GetSupportedPatterns();
if (patterns.Length > 0)
{
ValuePattern val = (ValuePattern)elmUrlBar.GetCurrentPattern(patterns[0]);
Debug.WriteLine("URL found: " + val.Current.Value);
}
}
}
catch { }
Debug.WriteLine(" Name: {0}, Id: {1}", name, id);
}
}
I have tried everything along similar lines in stackoverflow and different websites but is either really outdated or it just doesn't work.
Thanks in Advance.