如何在ListView中创建可点击的链接?

时间:2011-12-19 23:48:33

标签: c# winforms url listview

我正在尝试在ListView项目中点击URL。

我该怎么做?

我希望它工作的方式是用户以纯文本形式存储链接,然后当我检索链接时,我想让它们在ListView中可点击。

这是我在read.GetString(2)拉取URL值时从我的数据库中检索条目的方法:

if (security.DecryptAES
    (read.GetString(1), storedAuth.Password, 
    storedAuth.UserName) == "Web Site Password")
{
    // Count Web passwords.
    countWeb++;
    Web = new ListViewItem("");
    Web.SubItems.Add(security.DecryptAES
        (read.GetString(2), storedAuth.Password, storedAuth.UserName));
    Web.SubItems.Add(security.DecryptAES
        (read.GetString(5), storedAuth.Password, storedAuth.UserName));
    Web.SubItems.Add(security.DecryptAES
        (read.GetString(6), storedAuth.Password, storedAuth.UserName));
    Web.Tag = read.GetInt32(0);
    lvWeb.Items.Add(Web);
}

1 个答案:

答案 0 :(得分:12)

您要做的第一件事就是提供视觉反馈,让用户知道该项目是可点击的。我只是随意假设网址在第二列。为ListView添加MouseMove事件:

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

下一步非常相似,实现MouseUp事件以检测子项目上的点击:

    private void listView1_MouseUp(object sender, MouseEventArgs e) {
        var hit = listView1.HitTest(e.Location);
        if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1]) {
            var url = new Uri(hit.SubItem.Text);
            // etc..
        }
    }