在C#中获取程序图标?

时间:2012-07-04 06:28:09

标签: c# winforms visual-c#-express-2010

我有这个代码可以获取名称,但我如何获得每个程序的图标?

 string SoftwareKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products";
        RegistryKey rk = default(RegistryKey);
        rk = Registry.LocalMachine.OpenSubKey(SoftwareKey);

        string sname = string.Empty;

        foreach (string skname in rk.GetSubKeyNames())
        {

            try
            {
                sname = Registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("DisplayName").ToString();
                string Inst1 = Registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("InstallLocation").ToString();
                int n = dataGridView1.Rows.Add();
                dataGridView1.Rows[n].Cells[2].Value = sname; 
                dataGridView1.Rows[n].Cells[3].Value = Inst1;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

2 个答案:

答案 0 :(得分:4)

我不知道InstallProperties会为您提供已安装的可执行文件(因为安装程序确实可以安装多个可执行文件)。

如果您有办法确定正确的可执行文件(包括可能枚举InstallLocation中的.exe文件),则可以从该.exe中获取默认图标。

详情请见

Get File Icon used by Shell

<强>更新

以下代码未经测试,但应该非常接近:

string Inst1 = registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("InstallLocation").ToString();

foreach (string file in Directory.GetFiles(Inst1, "*.exe")) 
{
    string filePath = Path.Combine(Inst1, file);
    Icon  result = Icon.ExtractAssociatedIcon(filePath);
    // If result is not null, you have an icon.
}

答案 1 :(得分:2)

试试这个:

Icon  result = Icon.ExtractAssociatedIcon(filePath);