Search code examples
c#urllistviewclickable

My code causes URL to open in 2 different tabs, why?


As person helped me to figure out how to start open URL in default browser now I am having bit of a problem which causes to open URL in 2 different tabs when clicked. What could be the cause for this?

EDIT: I think it's good to point out that I am using a ListView in detailed mode. So when user clicks column with URL, it should open a single window in the browser.

lvWeb.MouseMove += new MouseEventHandler(lvWeb_MouseMove);
lvWeb.MouseUp +=new MouseEventHandler(lvWeb_MouseUp);

private void lvWeb_MouseMove(object sender, MouseEventArgs e)
{
    var hit = lvWeb.HitTest(e.Location);
    if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1]) 
        lvWeb.Cursor = Cursors.Hand;
    else lvWeb.Cursor = Cursors.Default;
}

private void lvWeb_MouseUp(object sender, MouseEventArgs e)
{
    var hit = lvWeb.HitTest(e.Location);
    if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1])
    {
        var url = new Uri(hit.SubItem.Text);
        System.Diagnostics.Process.Start(url.ToString());
    }
}

Solution

  • As one person sugested, I have visited the article which did the trick and it works as following:

        private string getDefaultBrowser()
        {
            string browser = string.Empty;
            RegistryKey key = null;
            try
            {
                key = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false);
    
                //trim off quotes
                browser = key.GetValue(null).ToString().ToLower().Replace("\"", "");
                if (!browser.EndsWith("exe"))
                {
                    //get rid of everything after the ".exe"
                    browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4);
                }
            }
            finally
            {
                if (key != null) key.Close();
            }
            return browser;
        }
    
        private void lvWeb_MouseUp(object sender, MouseEventArgs e)
        {
            var hit = lvWeb.HitTest(e.Location);
            if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1])
            {
                var url = new Uri(hit.SubItem.Text);
                //System.Diagnostics.Process.Start(url.ToString());
    
                Process p = new Process();
                p.StartInfo.FileName = getDefaultBrowser();
                p.StartInfo.Arguments = url.ToString();
                p.Start();
            }
        }