我的代码会导致URL在2个不同的标签中打开,为什么?

时间:2011-12-20 10:22:21

标签: c# url listview clickable

当人helped me想知道如何在默认浏览器中启动打开的URL时,我遇到了一个问题,导致在单击时在2个不同的选项卡中打开URL。可能是什么原因?

编辑:我认为最好指出我在详细模式下使用ListView。因此,当用户点击带有URL的列时,它应该在浏览器中打开一个窗口。

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());
    }
}

1 个答案:

答案 0 :(得分:3)

正如一个人建议的那样,我已经访问了article,它完成了这项工作,其工作原理如下:

    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();
        }
    }