将ListView项目中的图标显示到PictureBox

时间:2017-03-27 21:02:50

标签: c# .net winforms listview icons

我如何能够获取包含图标和文本的listView,然后显示在pictureBox中选择的listView图标?代码在进程中有一个按钮加载,在listView中有它们的图标。

listView看起来像这样:

Icons

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listView1.SelectedIndices.Count <= 0)
    {
        return;
    }
    int intselectedindex = listView1.SelectedIndices[0];
    if (intselectedindex >= 0)
    {
        textBox1.Text = listView1.Items[intselectedindex].Text;
        //pictureBox1.Image = ???
    }
}
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
    var query = "SELECT ProcessId, Name, ExecutablePath FROM Win32_Process";
    using (var searcher = new ManagementObjectSearcher(query))
    using (var results = searcher.Get())

    {
        var processes = results.Cast<ManagementObject>().Select(x => new
        {
            ProcessId = (UInt32)x["ProcessId"],
            Name = (string)x["Name"],
            ExecutablePath = (string)x["ExecutablePath"]
        });
        foreach (var p in processes)
        {
            if (System.IO.File.Exists(p.ExecutablePath))
            {
                listView1.LargeImageList = imageList1;
                var icon = Icon.ExtractAssociatedIcon(p.ExecutablePath);
                var key = p.ProcessId.ToString();
                this.imageList1.Images.Add(key, icon.ToBitmap());
                this.listView1.Items.Add(p.Name, key);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

由于您使用图像键将图像分配给项目,因此您可以通过以下方式获取所选项目的图像:

if (listView1.SelectedItems.Count == 1)
{
    var item = listView1.SelectedItems[0];
    if (item.ImageList != null)
        pictureBox1.Image = item.ImageList.Images[item.ImageKey];
}