title: C# Get the URL of the active tab of browser
body: <p>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.</p>
  <p>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.</p>
  <p>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</p>
  <pre><code>private void OnFocusChangedHandler(object src, AutomationFocusChangedEventArgs args)
          {
              Debug.WriteLine(&quot;Focus changed!&quot;);
              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 &gt; 0)
                          {
                              ValuePattern val = (ValuePattern)elmUrlBar.GetCurrentPattern(patterns[0]);
                              Debug.WriteLine(&quot;URL found: &quot; + val.Current.Value);
                              
                          }
                      }
                  }
                  catch { }
                  Debug.WriteLine(&quot;  Name: {0}, Id: {1}&quot;, name, id);
                  
              }
          }
  </code></pre>
  <p>I have tried everything along similar lines in stackoverflow and different websites but is either really outdated or it just doesn't work.</p>
  <p>Thanks in Advance.</p>