c# – Extract an application's icon

Question:

I need to get the application icon that is open on the screen. Application icons, browsers (examples get the chrome icon, word icon and so on…)

I tried to do it like this:

Process[] listProcesses = Process.GetProcesses();
        foreach (Process p in listProcesses)
        {
            Icon icon = Icon.ExtractAssociatedIcon(mo.MainModule.FileName);
            string uri = @"C:\imagens\" + p.ProcessName + ".ico";

            if (!File.Exists(uri))
            {

                FileStream stream = new FileStream(uri, FileMode.CreateNew);
                icon.Save(stream);

            } 

However I am getting the following error(Only part of a ReadProcessMemory or WriteProcessMemory request has completed).

Does anyone have any ideas??

Answer:

I believe that eventually some processes did not allow extracting the icon from them.

What I've done is add a try catch to continue execution if it fails.

Remembering that you will have to run the app with administrator permissions.

class Program
{
    static void Main(string[] args)
    {
        if (Elevate())
        {
            Process[] listProcesses = Process.GetProcesses();
            foreach (Process p in listProcesses)
            {
                try
                {
                    Icon icon = Icon.ExtractAssociatedIcon(p.MainModule.FileName);
                    string uri = @"C:\imagens\" + p.ProcessName + ".ico";

                    if (!File.Exists(uri))
                    {
                        FileStream stream = new FileStream(uri, FileMode.CreateNew);
                        icon.Save(stream);
                        stream.Close();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(p.ProcessName + " - " + ex.Message);
                }
            }

        }
        else
        {
            Console.WriteLine("Execute o app com privilégios elevados");
        }

        Console.ReadKey();
    }

    public static bool Elevate()
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();

        WindowsPrincipal role = new WindowsPrincipal(user);

        if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
        {
            return false;
        }

        if (user == null)
        {
            return false;
        }

        return role.IsInRole(WindowsBuiltInRole.Administrator);
    }
}

Another point I changed was the Platform target for x64

Scroll to Top
AllEscort