在C#中获取程序图标?

3
我有这段代码可以获取程序名称,但是如何获取每个程序的图标呢?
 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个回答

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.
}

我正在使用C#,那么我该怎么做? - Hunter Mitchell
添加了代码以展示如何搜索给定文件夹中的.exe文件并提取图标。我不记得Directory.GetFiles()是否只返回文件名还是文件的完整路径,所以您可能不需要Path.Combine行。感谢@ebad86提供简洁的获取图标方法。 - Eric J.

2

试试这个:

Icon  result = Icon.ExtractAssociatedIcon(filePath); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接