Пример #1
0
        private void btnPickFile_Click(object sender, EventArgs e)
        {
            var result = iconPickerDialog.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                var fileName = iconPickerDialog.FileName;
                m_iconIndex = iconPickerDialog.IconIndex;

                Icon   icon       = null;
                Icon[] splitIcons = null;
                try
                {
                    if (Path.GetExtension(iconPickerDialog.FileName).ToLower() == ".ico")
                    {
                        m_iconExtractor = null;
                        icon            = new Icon(iconPickerDialog.FileName);
                    }
                    else
                    {
                        m_iconExtractor = new IconExtractor(fileName);
                        icon            = m_iconExtractor.GetIcon(m_iconIndex);
                    }

                    splitIcons = IconUtil.Split(icon);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                txtFileName.Text = String.Format(
                    "{0}, #{1}, {2} variations", fileName, m_iconIndex, splitIcons.Length);

                // Update icons.

                Icon = icon;
                icon.Dispose();

                lvwIcons.BeginUpdate();
                ClearAllIcons();

                foreach (var i in splitIcons)
                {
                    var item = new IconListViewItem();
                    var size = i.Size;
                    item.BitCount    = IconUtil.GetBitCount(i);
                    item.Bitmap      = IconUtil.ToBitmap(i);
                    item.ToolTipText = String.Format("{0}x{1}, {2} bits", size.Width, size.Height, item.BitCount);
                    i.Dispose();

                    lvwIcons.Items.Add(item);
                }

                lvwIcons.EndUpdate();

                btnSaveAsIco.Enabled = (m_iconExtractor != null);
            }
        }
Пример #2
0
        private static Icon[] GetIcons(string filename)
        {
            Icon[]        splitIcons = new Icon[0];
            IconExtractor ie         = new IconExtractor(filename);

            if (ie.Count > 0)
            {
                splitIcons = IconUtil.Split(ie.GetIcon(0));
            }
            return(splitIcons);
        }
Пример #3
0
        ///<exception cref="Exception"></exception>
        public static BitmapSource ExtractIconFromEXEDLL(string exeordllPath, int iconIndex, int width, int height)
        {
            System.Drawing.Icon   fullIcon  = new IconExtractor(exeordllPath).GetIcon(iconIndex);          //Throws if invalid path or index
            System.Drawing.Icon[] splitIcon = IconUtil.Split(fullIcon);
            System.Drawing.Icon   selectedIcon;
            if (splitIcon.Count() == 0)
            {
                throw new InvalidOperationException("The icon contains no sizes");
            }
            try {
                selectedIcon = (
                    splitIcon
                    .Last((icon) => {
                    return(icon.Width == width && icon.Height == height);
                })                         //Throws if no icons match
                    );
            } catch (InvalidOperationException) {
                IEnumerable <System.Drawing.Icon> largerIcons = (
                    splitIcon
                    .Where((icon) => {
                    return(icon.Width >= width && icon.Height >= height);
                })
                    );
                IEnumerable <System.Drawing.Icon> selectedIcons1;
                if (largerIcons.Count() == 0)
                {
                    selectedIcons1 = splitIcon;
                }
                else
                {
                    selectedIcons1 = largerIcons;
                }

                IEnumerable <System.Drawing.Icon> inProportionIcons = (
                    selectedIcons1.Where((icon) => {
                    return(icon.Width / icon.Height == width / height);
                })
                    );

                if (inProportionIcons.Count() == 0)
                {
                    selectedIcon = inProportionIcons.Best((icon) => {
                        return(Math.Abs((icon.Width - width)) * -1);
                    }, true);
                }
                else
                {
                    selectedIcon = selectedIcons1.Best((icon) => {
                        return(Math.Abs(((icon.Width * icon.Height) - (width * height))) * -1);
                    }, true);
                }
            }
            return(BitmapToBitmapSource(IconUtil.ToBitmap(selectedIcon)));            //Might throw exceptions
        }
        private void BuildListView()
        {
            //reset the list view items
            lvwIcons.Items.Clear();

            //validate the path exists
            var targetPath = txtPathToExtractFrom.Text;

            if (!File.Exists(targetPath))
            {
                return;
            }

            lvwIcons.BeginUpdate();
            try
            {
                //icon files don't need extraction
                if (string.Equals(Path.GetExtension(targetPath), ".ico", StringComparison.InvariantCultureIgnoreCase))
                {
                    _icons = new[] { new Icon(targetPath) };
                }
                else
                {
                    var iconExtraction = new IconExtractor(targetPath);
                    _icons = iconExtraction.GetAllIcons();
                }

                foreach (var i in _icons)
                {
                    var splitIcons = IconUtil.Split(i);

                    var largestIcon = splitIcons.OrderByDescending(k => k.Width)
                                      .ThenByDescending(k => Math.Max(k.Height, k.Width))
                                      .First();

                    var item = new IconListViewItem {
                        Bitmap = IconUtil.ToBitmap(largestIcon)
                    };
                    i.Dispose();
                    largestIcon.Dispose();

                    lvwIcons.Items.Add(item);
                }
            }
            catch
            {
                // ignored
            }
            finally
            {
                lvwIcons.EndUpdate();
            }
        }
Пример #5
0
 private void exctractIcon(string path)
 {
     try
     {
         IconExtractor ie         = new IconExtractor(path);
         Icon          icon       = ie.GetIcon(0);
         MultiIcon     mIcon      = new MultiIcon();
         SingleIcon    sIcon      = mIcon.Add("oink");
         Icon[]        splitIcons = IconUtil.Split(icon);
         sIcon.CreateFrom(IconUtil.ToBitmap(splitIcons[splitIcons.Length - 1]), IconOutputFormat.Vista);
         sIcon.Save(applicationPath + iconName);
     }
     catch { }
 }
Пример #6
0
        private void LoadAURL(string filePath, TextBox entry)
        {
            string LinkTarget           = "";
            string LinkArguments        = "";
            string LinkIconLocation     = "";
            string LinkWorkingDirectory = "";
            int    LinkIconIndex        = 0;
            string LinkDescription      = "";


            StringBuilder temp = new StringBuilder(255);
            int           i    = GetPrivateProfileString("InternetShortcut", "URL", "", temp, 255, filePath);

            LinkTarget       = temp.ToString();
            i                = GetPrivateProfileString("InternetShortcut", "IconFile", "", temp, 255, filePath);
            LinkIconLocation = temp.ToString();
            i                = GetPrivateProfileString("InternetShortcut", "IconIndex", "", temp, 255, filePath);
            LinkIconIndex    = Convert.ToInt32(temp.ToString());

            MenuEntry thisEntry = new MenuEntry();

            thisEntry.TargetOriginal   = LinkTarget;
            thisEntry.Target           = LinkTarget;
            thisEntry.Arguments        = LinkArguments;
            thisEntry.IconPathOriginal = LinkIconLocation;
            thisEntry.IconIndex        = LinkIconIndex;
            thisEntry.StartIn          = LinkWorkingDirectory;
            thisEntry.Description      = LinkDescription;

            FileInfo lnk = new FileInfo(filePath);
            //            string iconfilename = IconFolder + @"\" + LinkIconLocation.Substring(LinkIconLocation.LastIndexOf("/") + 1);

            string iconfilename = IconFolder + @"\" + lnk.Name.Substring(0, lnk.Name.Length - lnk.Extension.Length) + ".ico";

            var client = new System.Net.WebClient();

            client.DownloadFile(LinkIconLocation, iconfilename);

            Icon icon = new Icon(iconfilename);

            splitIcons = IconUtil.Split(icon);
            iconCount  = splitIcons.GetUpperBound(0);

            Image1.Image    = splitIcons[0].ToBitmap();
            IconNumber.Text = "0";
            IconSize.Text   = splitIcons[0].Width.ToString() + "x" + splitIcons[0].Height.ToString();
            SetItem(thisEntry);
        }
Пример #7
0
        private void btnLoadIcon_Click(object sender, EventArgs e)
        {
            using (var ofd = new OpenFileDialog())
            {
                ofd.FileName = string.Empty;
                ofd.Filter   = Resources.IconFilter;
                if (ofd.ShowDialog() != DialogResult.OK || Path.GetExtension(ofd.FileName) != ".ico")
                {
                    return;
                }

                _icon = new Icon(ofd.FileName);
                var icons       = IconUtil.Split(_icon);
                var biggesticon = icons.Aggregate((icon1, icon2) => icon1.Width * icon1.Height > icon2.Width * icon2.Height ? icon1 : icon2);
                pictureBox1.Image = IconUtil.ToBitmap(biggesticon);
            }
        }
        public ApplicationPicker_Control(GameApplication app) : base()
        {
            Orientation = Orientation.Horizontal;

            _iconExtractor = new IconExtractor(app.ExecutablePath);
            int iconCount = _iconExtractor.Count;

            System.Drawing.Icon[] splitIcons = IconUtil.Split(_iconExtractor.GetIcon(0));
            ImageSource           imageSource;

            System.Drawing.Bitmap bitmap;
            try
            {
                int c = 0;
                do
                {
                    bitmap = IconUtil.ToBitmap(splitIcons[c]);
                    c++;
                }while (bitmap.Size.Width < 256 && c >= 0 && c < splitIcons.Length);
            }
            catch (Exception)
            {
                throw;
            }
            var stream = new MemoryStream();

            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            imageSource = BitmapFrame.Create(stream);

            Children.Add(new Image()
            {
                Source            = imageSource,
                VerticalAlignment = VerticalAlignment.Center,
                MaxHeight         = 75,
                MaxWidth          = 75,
                Margin            = new Thickness(0, 0, 20, 0)
            });

            Children.Add(new TextBlock()
            {
                Text = app.Name,
                VerticalAlignment = VerticalAlignment.Center,
                FontSize          = 25
            });
            App = app;
        }
Пример #9
0
        private byte[] GetLogoBytes()
        {
            var splitIcons = IconUtil.Split(_icons[lvwIcons.SelectedItems[0].Index]);

            byte[] byteArray;
            using (var stream = new MemoryStream())
            {
                using (var bitmapLoad = Bitmap.FromHicon(splitIcons.OrderByDescending(k => k.Width)
                                                         .ThenByDescending(k => k.Height)
                                                         .First().Handle))
                {
                    bitmapLoad.Save(stream, ImageFormat.Png);

                    byteArray = stream.ToArray();
                }
            }
            return(byteArray);
        }
Пример #10
0
        private void pcIcon_Click(object sender, EventArgs e)
        {
            var iconPickerDialog = new IconPickerDialog();

            if (iconPickerDialog.ShowDialog(this) == DialogResult.OK)
            {
                _iconIndex = iconPickerDialog.IconIndex;

                var extractor = new IconExtractor(iconPickerDialog.FileName);
                var icon      = extractor.GetIcon(iconPickerDialog.IconIndex);

                var splitIcons  = IconUtil.Split(icon);
                var maxSizeIcon = splitIcons.Where(f => f.Height == splitIcons.Max(m => m.Height)).ToList();

                if (maxSizeIcon.Any())
                {
                    pcIcon.Image = IconUtil.ToBitmap(maxSizeIcon[maxSizeIcon.Count() - 1]);
                }
            }
        }
Пример #11
0
        private void btnClone_Click(object sender, EventArgs e)
        {
            using (var ofd = new OpenFileDialog())
            {
                ofd.FileName = string.Empty;
                ofd.Filter   = Resources.ExeFilter;
                if (ofd.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                var iconextractor = new IconExtractor(ofd.FileName);
                var icons         = IconUtil.Split(iconextractor.GetIcon(0));
                _icon = iconextractor.GetIcon(0);
                var biggesticon = icons.Aggregate((icon1, icon2) => icon1.Width * icon1.Height > icon2.Width * icon2.Height ? icon1 : icon2);
                pictureBox1.Image = IconUtil.ToBitmap(biggesticon);

                _fileToCloneLocation = ofd.FileName;
            }
        }
Пример #12
0
 private static void AudioSession(AudioSessionControl session)
 {
     using (var audiosession = session.QueryInterface <AudioSessionControl2>())
     {
         int id;
         audiosession.GetProcessIdNative(out id);
         string name = "";
         if (id != 0)
         {
             Process currentprocess = Process.GetProcessById(id);
             name = currentprocess.MainModule.ModuleName;
             //Icon ico = Icon.ExtractAssociatedIcon(currentprocess.MainModule.FileName);
             IconExtractor ie         = new IconExtractor(currentprocess.MainModule.FileName);
             Icon[]        splitIcons = IconUtil.Split(ie.GetIcon(0));
         }
         else
         {
             name = "System Sounds";
         }
         Console.WriteLine(id);
         Console.WriteLine(name);
     }
 }
Пример #13
0
        private void LoadAFile(string filePath, TextBox entry)
        {
            // we have an internet shortcut
            FileInfo  lnk       = new FileInfo(filePath);
            MenuEntry thisEntry = new MenuEntry();

            thisEntry.TargetOriginal = "";
            thisEntry.Target         = "";
            thisEntry.Arguments      = filePath;
            thisEntry.IconPath       = "";
            thisEntry.IconIndex      = 0;
            thisEntry.PanelName      = entry.Name;
            thisEntry.StartIn        = lnk.DirectoryName;
            thisEntry.Description    = "FILE";

            string iconfilename = IconFolder + @"\" + lnk.Name.Substring(0, lnk.Name.Length - lnk.Extension.Length) + ".ico";

            String programName = AssocQueryString(AssocStr.Executable, lnk.Extension);

            Image1.Image = null;
            if (programName != null)
            {
                IconExtractor extractor = new IconExtractor(programName.ToString());
                Icon          icon      = extractor.GetIcon(thisEntry.IconIndex);

                splitIcons = IconUtil.Split(icon);
                iconCount  = splitIcons.GetUpperBound(0);

                Image1.Image = splitIcons[0].ToBitmap();
            }
            IconNumber.Text = "0";

            thisEntry.IconPath = iconfilename;

            SetItem(thisEntry);
        }
Пример #14
0
        private void btnPickFile_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog()
            {
                Filter = "Icons (*.exe;*.ico;*.dll;*.lnk)|*.exe;*.ico;*.dll;*.lnk|All files (*.*)|*.*",
                //DereferenceLinks = true, // This thing doesn't work sadly, idk why
                Title = "Pick an icon (.ico) or a file containing an icon (.exe, .dll)"
            })
            {
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    FileInfo fileInfo = new FileInfo(openFileDialog.FileName);

                    // Dereference link cause MS can't make it work on OpenFileDialog
                    if (fileInfo.Extension == ".lnk")
                    {
                        iconPickerDialog.FileName = Symlink.ResolveShortcut(fileInfo.FullName);
                    }
                    else
                    {
                        iconPickerDialog.FileName = fileInfo.FullName;
                    }

                    if (iconPickerDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        var fileName = iconPickerDialog.FileName;
                        var index    = iconPickerDialog.IconIndex;

                        // Set FileName to further retrieve it
                        FileName = Path.GetFileNameWithoutExtension(fileName);

                        Icon   icon       = null;
                        Icon[] splitIcons = null;
                        try
                        {
                            if (Path.GetExtension(iconPickerDialog.FileName).ToLower() == ".ico")
                            {
                                icon = new Icon(iconPickerDialog.FileName);
                            }
                            else
                            {
                                var extractor = new IconExtractor(fileName);
                                icon = extractor.GetIcon(index);
                            }

                            splitIcons = IconUtil.Split(icon);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        txtFileName.Text = string.Format("{0}, #{1}, {2} variations", fileName, index, splitIcons.Length);

                        // Update icons.

                        Icon = icon;
                        icon.Dispose();

                        lvwIcons.BeginUpdate();
                        ClearAllIcons();

                        foreach (var i in splitIcons)
                        {
                            // Exclude all icons which size is > 256 (Throw "Generic GDI+ error" when converting if size > 128x128)
                            if (i.Width > 128 || i.Height > 128)
                            {
                                continue;
                            }

                            var item = new IconListViewItem();
                            var size = i.Size;
                            var bits = IconUtil.GetBitCount(i);
                            item.ToolTipText = string.Format("{0}x{1}, {2} bits", size.Width, size.Height, bits);
                            item.Bitmap      = IconUtil.ToBitmap(i);
                            i.Dispose();

                            lvwIcons.Items.Add(item);
                        }

                        lvwIcons.EndUpdate();
                    }
                    else if (firstOpen)
                    {
                        DialogResult = DialogResult.Cancel;
                        this.Hide();
                    }
                }
            }
        }
Пример #15
0
        public static Bitmap getIconX(string fn)
        {
            Icon          icon;
            IconExtractor ie;

            FileInfo inf = new FileInfo(fn);

            if (inf.Extension.ToLower() != ".exe")
            {
                return(Extends.IconHelper.IconReader.GetFileIcon(fn, IconHelper.IconReader.IconSize.Small, false).ToBitmap());
            }

            try
            {
                ie = new IconExtractor(fn);
            }
            catch (Exception) {
                return(null);
            }



            // Get the full name of the associated file.

            string fileName = ie.FileName;

            // Get the count of icons in the associated file.

            int iconCount = ie.Count;

            // Extract icons individually.

            Icon icon0 = ie.GetIcon(0);

            // Extract all the icons in one go.

            Icon[] allIcons = ie.GetAllIcons();

            // -----------------------------------------------------------------------------
            // Usage of IconUtil class:

            // Split the variations of icon0 into separate icon objects.

            Icon[] splitIcons = IconUtil.Split(icon0);

            // Convert an icon into bitmap. Unlike Icon.ToBitmap() it preserves the transparency.
            Icon bestOne = null;

            foreach (Icon i in splitIcons)
            {
                if (bestOne == null && i.Height <= Vars.MAXIMUM_ICON_SIZE.Height)
                {
                    bestOne = i;
                }
                if (bestOne != null && i.Height > bestOne.Height && i.Height <= Vars.MAXIMUM_ICON_SIZE.Height)
                {
                    bestOne = i;
                }
            }

            //Bitmap bitmap = splitIcons[0].ToBitmap();

            // Get the bit count of an icon.

            //int bitDepth = IconUtil.GetBitCount(splitIcons[2]);



            return((bestOne ?? Properties.Resources.app_icon).ToBitmap());
        }
Пример #16
0
        static void Main(string[] args)
        {
            List <WindowsProgram> installedPrograms = new List <WindowsProgram>();
            string registryKey_AppPaths             = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";

            //Get executables
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey_AppPaths))
            {
                foreach (string subkeyName in key.GetSubKeyNames())
                {
                    using (RegistryKey subkey = key.OpenSubKey(subkeyName))
                    {
                        object rawLocation = subkey.GetValue("");
                        object rawPath     = subkey.GetValue("Path");
                        if (rawLocation is null)
                        {
                            continue;
                        }
                        if (rawPath is null)
                        {
                            continue;
                        }

                        WindowsProgram app = new WindowsProgram();
                        app.executableLocation = rawLocation.ToString();
                        app.installLocation    = rawPath.ToString();
                        installedPrograms.Add(app);
                    }
                }
            }

            foreach (WindowsProgram app in installedPrograms)
            {
                if (!File.Exists(app.executableLocation))
                {
                    continue;
                }

                var versionInfo = FileVersionInfo.GetVersionInfo(app.executableLocation);
                app.applicationName = versionInfo.FileDescription;
                app.publisherName   = versionInfo.CompanyName;
                app.iconPaths       = new List <string>();

                IconExtractor ie = new IconExtractor(app.executableLocation);
                if (ie.Count == 0)
                {
                    continue;
                }
                Icon   icon           = ie.GetIcon(0);
                Icon[] iconVariations = IconUtil.Split(icon);


                string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string iconPath     = assemblyPath + @"\icons\";
                if (!Directory.Exists(iconPath))
                {
                    Directory.CreateDirectory(iconPath);
                }

                for (int a = 0; a < iconVariations.Count(); a++)
                {
                    string iconExportName = Path.GetFileName(app.executableLocation) + "_" + a + ".png";
                    Bitmap iconAsBitmap   = iconVariations[a].ToBitmap();
                    iconAsBitmap.Save(iconPath + iconExportName, ImageFormat.Png);
                    app.iconPaths.Add(iconPath + iconExportName);
                }
            }



            string jsonString = JsonSerializer.Serialize(installedPrograms);

            Console.WriteLine(jsonString);
        }
Пример #17
0
        private void LoadAShortcut(string filePath, TextBox entry)
        {
            FileInfo lnk = new FileInfo(filePath);

            try
            {
                //MessageBox.Show(linkInfo.ToString());
                //string LinkTarget = Environment.ExpandEnvironmentVariables(((linkInfo.LinkTargetIDList == null || linkInfo.LinkTargetIDList.Path == null) ? linkInfo.StringData.NameString : linkInfo.LinkTargetIDList.Path)).Replace("@", "");
                string LinkTarget           = "";
                string LinkArguments        = "";
                string LinkIconLocation     = "";
                string LinkWorkingDirectory = "";
                int    LinkIconIndex        = 0;
                string LinkDescription      = "";

                WshShell     shell    = new WshShell();
                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(filePath);

                LinkTarget           = Environment.ExpandEnvironmentVariables(shortcut.TargetPath);
                LinkArguments        = shortcut.Arguments;
                LinkIconLocation     = Environment.ExpandEnvironmentVariables(shortcut.IconLocation);
                LinkWorkingDirectory = Environment.ExpandEnvironmentVariables(shortcut.WorkingDirectory);
                if (LinkIconLocation.Contains(","))
                {
                    LinkIconIndex = Convert.ToInt32(LinkIconLocation.Substring(LinkIconLocation.LastIndexOf(",") + 1));
                }
                else
                if (LinkTarget.Contains(","))
                {
                    LinkIconIndex = Convert.ToInt32(LinkTarget.Substring(LinkTarget.LastIndexOf(",") + 1));
                }
                LinkDescription = shortcut.Description;

                MenuEntry thisEntry = new MenuEntry();
                thisEntry.TargetOriginal = LinkTarget;
                thisEntry.Target         = LinkTarget;
                if (LinkTarget.IndexOf(",") > 0)
                {
                    thisEntry.Target = LinkTarget.Substring(0, LinkTarget.LastIndexOf(","));
                }
                thisEntry.Arguments        = LinkArguments;
                thisEntry.IconPathOriginal = LinkIconLocation;
                thisEntry.IconPath         = LinkIconLocation;
                if (LinkIconLocation.IndexOf(",") > 0)
                {
                    thisEntry.IconPath = LinkIconLocation.Substring(0, LinkIconLocation.LastIndexOf(","));
                }
                else
                if (LinkIconLocation.IndexOf(",") == 0)
                {
                    thisEntry.IconPath = thisEntry.Target;
                }
                thisEntry.IconIndex   = LinkIconIndex;
                thisEntry.PanelName   = entry.Name;
                thisEntry.StartIn     = LinkWorkingDirectory;
                thisEntry.Description = LinkDescription;

                /*
                 *
                 * If LinkIconPath == LinkTarget
                 *      Get the first icon
                 * If LinkIconIndex == 0
                 *      Get the first icon
                 * else
                 *      Get the correct icon
                 */

                /*Icon can be
                 *  ico
                 *  icl indexed
                 *  exe indexed?
                 *  dll indexed?
                 *
                 *
                 *
                 * */

                //if the iconpath exists then work from that
                if (System.IO.File.Exists(thisEntry.IconPath))
                {
                    FileInfo f = new FileInfo(thisEntry.IconPath);
                    if ((f.Extension.ToLower() == ".png"))
                    {
                        Image1.Image = Image.FromFile(thisEntry.IconPath);
                    }
                    else
                    if ((f.Extension.ToLower() == ".ico"))
                    {
                        Image1.Image = Image.FromFile(thisEntry.IconPath);
                    }
                    else
                    if ((f.Extension.ToLower() == ".exe") || (f.Extension.ToLower() == ".dll"))
                    {
                        IconExtractor extractor = new IconExtractor(thisEntry.IconPath);
                        Icon          icon      = extractor.GetIcon(thisEntry.IconIndex);

                        if (icon != null)
                        {
                            splitIcons = IconUtil.Split(icon);
                            iconCount  = splitIcons.GetUpperBound(0);

                            //Icon ico = Icon.ExtractAssociatedIcon(filePath);
                            Image1.Image    = splitIcons[0].ToBitmap();
                            IconNumber.Text = "0";
                        }
                    }
                    else
                    //other files like icl
                    {
                        IconExtractor extractor = new IconExtractor(thisEntry.IconPath);
                        Icon          icon      = extractor.GetIcon(thisEntry.IconIndex);

                        if (icon != null)
                        {
                            splitIcons = IconUtil.Split(icon);
                            iconCount  = splitIcons.GetUpperBound(0);

                            //Icon ico = Icon.ExtractAssociatedIcon(filePath);
                            Image1.Image    = splitIcons[0].ToBitmap();
                            IconNumber.Text = "0";
                        }
                    }
                }
                else
                {
                    // the filename in the iconpath does not exist
                    // or there is no value in the iconpath
                    FileInfo f = new FileInfo(thisEntry.Target);
                    if (Directory.Exists(thisEntry.Target))
                    {
                        //we have a target that is a folder
                        //if the target is a folder and no iconfile is specified just make it the standard folder icon
                        string iconfilename = IconFolder + @"\" + f.Name.Substring(0, f.Name.Length - f.Extension.Length) + ".ico";
                        Icon   ico          = ExtractFromPath(thisEntry.Target);
                        Image1.Image = ico.ToBitmap();
                    }
                    else
                    {
                        if (System.IO.File.Exists(thisEntry.Target))
                        {
                            //We have a target that is a file of some type
                            string        iconfilename = IconFolder + @"\" + f.Name.Substring(0, f.Name.Length - f.Extension.Length) + ".ico";
                            IconExtractor extractor    = new IconExtractor(filePath);
                            Icon          icon         = extractor.GetIcon(thisEntry.IconIndex);

                            if (icon != null)
                            {
                                splitIcons = IconUtil.Split(icon);
                                iconCount  = splitIcons.GetUpperBound(0);

                                //Icon ico = Icon.ExtractAssociatedIcon(filePath);
                                Image1.Image    = splitIcons[0].ToBitmap();
                                IconNumber.Text = "0";
                            }
                            else
                            {
                                Image1.Image    = null;
                                IconNumber.Text = "0";
                            }
                        }
                        else
                        {
                            MessageBox.Show("Link Target does not exist", "Fiel doesn't exist", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }

                SetItem(thisEntry);
            }
            catch (Exception ex)
            {
                // Target cannot be processed
                MessageBox.Show("Link " + filePath + "caused an error - " + ex.Message, "Link Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #18
0
        public static void Main(string[] args)
        {
            bool exportBase64 = true;

            AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
            //App.Main();
            //global::App.Main();
            //LS4W.App.Main();

            List <WindowsProgram> installedPrograms = new List <WindowsProgram>();
            string registryKey_AppPaths             = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";

            //Get executables
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey_AppPaths))
            {
                foreach (string subkeyName in key.GetSubKeyNames())
                {
                    using (RegistryKey subkey = key.OpenSubKey(subkeyName))
                    {
                        object rawLocation = subkey.GetValue("");
                        object rawPath     = subkey.GetValue("Path");
                        if (rawLocation is null)
                        {
                            continue;
                        }
                        if (rawPath is null)
                        {
                            continue;
                        }

                        WindowsProgram app = new WindowsProgram();
                        app.executableLocation = rawLocation.ToString();
                        app.installLocation    = rawPath.ToString();
                        app.iconPaths          = new List <string>();


                        if (!File.Exists(app.executableLocation))
                        {
                            continue;
                        }

                        string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                        string iconPath     = assemblyPath + @"\icons\";
                        if (!Directory.Exists(iconPath))
                        {
                            Directory.CreateDirectory(iconPath);
                        }

                        IconExtractor ie = new IconExtractor(app.executableLocation);
                        if (ie.Count == 0) //contains no icons
                        {
                            continue;
                        }

                        List <Icon> iconVariations = IconUtil.Split(ie.GetIcon(0)).ToList();
                        foreach (var(icon, index) in iconVariations.WithIndex())
                        {
                            string iconExportName = Path.GetFileName(app.executableLocation) + "_" + index + ".png";
                            Bitmap iconAsBitmap   = icon.ToBitmap();
                            iconAsBitmap.Save(iconPath + iconExportName, ImageFormat.Png);
                            app.iconPaths.Add(iconPath + iconExportName);
                        }

                        if (exportBase64)
                        {
                            Icon   largestIcon  = iconVariations.OrderByDescending(icon => icon.Width).First();
                            Bitmap iconAsBitmap = largestIcon.ToBitmap();
                            using (MemoryStream ms = new MemoryStream())
                            {
                                iconAsBitmap.Save(ms, ImageFormat.Png);
                                byte[] iconAsBytes = ms.ToArray();
                                app.iconB64 = Convert.ToBase64String(iconAsBytes);
                            }
                        }

                        installedPrograms.Add(app);
                    }
                }
            }

            string jsonString = JsonSerializer.Serialize(installedPrograms);

            Console.WriteLine(jsonString);
        }
Пример #19
0
        private void BuildListView()
        {
            //reset the list view items
            lvwIcons.Items.Clear();

            //validate the path exists
            var targetPath = txtPathToExtractFrom.Text;

            if (!File.Exists(targetPath))
            {
                return;
            }

            try
            {
                //Get the icons
                //icon files don't need extraction
                if (string.Equals(Path.GetExtension(targetPath), ".ico", StringComparison.InvariantCultureIgnoreCase))
                {
                    _icons = new[] { new Icon(targetPath) };
                }
                else
                {
                    var iconExtraction = new IconExtractor(targetPath);
                    _icons = iconExtraction.GetAllIcons();
                }

                //Build the list view items
                var items = new List <IconListViewItem>();
                foreach (Icon icon in _icons)
                {
                    var splitIcons = IconUtil.Split(icon);

                    var largestIcon = splitIcons.OrderByDescending(k => k.Width)
                                      .ThenByDescending(k => Math.Max(k.Height, k.Width))
                                      .First();
                    Bitmap bmp;
                    try
                    {
                        bmp = IconUtil.ToBitmap(largestIcon);
                    }
                    catch
                    {
                        //icon failed to convert to bitmap
                        continue;
                    }
                    items.Add(new IconListViewItem(bmp));

                    //Icon cleanup
                    icon.Dispose();
                    Array.ForEach(splitIcons, ic => ic.Dispose());
                    //The listview creates its own copy of the bitmap
                    bmp.Dispose();
                }
                lvwIcons.Items.AddRange(items);
            }
            catch (Exception)
            {
                // ignored
            }
        }
        private void btnPickFile_Click(object sender, EventArgs e)
        {
            if (iconPickerDialog.ShowDialog(this) == DialogResult.OK)
            {
                var fileName = iconPickerDialog.FileName;
                var index    = iconPickerDialog.IconIndex;

                Icon   icon       = null;
                Icon[] splitIcons = null;
                try
                {
                    if (Path.GetExtension(iconPickerDialog.FileName).ToLower() == ".ico")
                    {
                        icon = new Icon(iconPickerDialog.FileName);
                    }
                    else
                    {
                        var extractor = new IconExtractor(fileName);
                        icon = extractor.GetIcon(index);
                    }

                    splitIcons = IconUtil.Split(icon);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                txtFileName.Text = String.Format("{0}, #{1}, {2} variations", fileName, index, splitIcons.Length);

                // Update icons.

                Icon = icon;
                icon.Dispose();

                lvwIcons.BeginUpdate();
                ClearAllIcons();

                foreach (var i in splitIcons)
                {
                    // Exclude all icons which size is > 256 (Throw "Generic GDI+ error" when converting if size > 128x128)
                    if (i.Width > 128 || i.Height > 128)
                    {
                        continue;
                    }

                    var item = new IconListViewItem();
                    var size = i.Size;
                    var bits = IconUtil.GetBitCount(i);
                    item.ToolTipText = String.Format("{0}x{1}, {2} bits", size.Width, size.Height, bits);
                    item.Bitmap      = IconUtil.ToBitmap(i);
                    i.Dispose();

                    lvwIcons.Items.Add(item);
                }

                lvwIcons.EndUpdate();
            }
            else if (firstOpen)
            {
                DialogResult = DialogResult.Cancel;
                this.Hide();
            }
        }
Пример #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static List <Bitmap> fun_exe_img(String fileName)
        {
            List <Bitmap> ar_Bitmap_2 = new List <Bitmap>();



            Icon icon = null;

            Icon[]        splitIcons = null;
            IconExtractor extractor  = null;

            try {
                extractor = new IconExtractor(fileName);
            } catch {
                return(null);
            }

            //同一個執行檔,會有很多套不同的icon
            for (int k = 0; k < extractor.Count; k++)
            {
                List <Bitmap> ar_Bitmap = new List <Bitmap>();//該套icon裡面的所有size

                try {
                    icon       = extractor.GetIcon(k);
                    splitIcons = IconUtil.Split(icon);
                } catch {
                    continue;
                }


                // Update icons.
                foreach (var i in splitIcons)
                {
                    try {
                        //var size = i.Size;
                        //var bits = IconUtil.GetBitCount(i);
                        ar_Bitmap.Add(IconUtil.ToBitmap(i));
                        i.Dispose();
                    } catch {
                        continue;
                    }
                }

                //排序(由大到小
                for (int i = 0; i < ar_Bitmap.Count; i++)
                {
                    for (int j = i; j < ar_Bitmap.Count; j++)
                    {
                        if (ar_Bitmap[i].Width < ar_Bitmap[j].Width)
                        {
                            Bitmap bb = ar_Bitmap[i];
                            ar_Bitmap[i] = ar_Bitmap[j];
                            ar_Bitmap[j] = bb;
                        }
                    }
                }

                //放入要回傳的陣列
                foreach (var item in ar_Bitmap)
                {
                    if (item != null)
                    {
                        if (item.Width > 5)
                        {
                            ar_Bitmap_2.Add(item);
                        }
                    }
                }
            }//for



            return(ar_Bitmap_2);
        }
Пример #22
0
        /// <summary>
        /// Gets the file icon of an .exe
        /// </summary>
        /// <param name="fileLocation"></param>
        /// <returns></returns>
        private ImageSource GetFileIcon(string fileLocation)
        {
            //extract icon
            IconExtractor iconExtractor = new IconExtractor(fileLocation);

            //get main icon
            Icon icon = iconExtractor.GetIcon(0);

            //split the icon (as there are multiple sizes embeded)
            Icon[] splitIcons = IconUtil.Split(icon);

            //dispose of the original icon object since we no longer need it
            icon.Dispose();

            //the highest quality icon, will be assigned later
            Icon iconHQ;

            //pixel width, will be changed through iterations and compared
            int width = 0;

            //the index of the highest quality one we find in the list
            int hqIndex = 0;

            //run a loop through the icon list to get highest quality icon
            for (int i = 0; i < splitIcons.Length; i++)
            {
                //if the pixel width is bigger than our width variable then assign it
                if (splitIcons[i].Width > width)
                {
                    //assign the pixel width (used for comparison later)
                    width = splitIcons[i].Width;

                    //get the index of the element
                    hqIndex = i;
                }
            }

            //if the loop finds the one with the highest quality, then use it using the hq index
            iconHQ = splitIcons[hqIndex];

            //convert the icon to a bitmap
            Bitmap bitmap = IconUtil.ToBitmap(iconHQ);

            //create a temporary path for it
            string tempPath = appSettings.Get_App_ConfigDirectory() + "tempIconPreview.bmp";

            //if there is already a file of the same name, get rid of it
            if (System.IO.File.Exists(tempPath))
            {
                IOManagement.DeleteFile(tempPath);
            }

            //save the bitmap to the temp path we defined
            bitmap.Save(tempPath);

            //clear the original object if it isn't already
            if (bitmapimage != null)
            {
                bitmapimage = null;
            }

            //initallize our bitmap image object with a new one (not the same as the bitmap we defined prior)
            bitmapimage = new BitmapImage();
            bitmapimage.BeginInit();                                       //initalize the image
            bitmapimage.UriSource   = new Uri(tempPath, UriKind.Absolute); //set the path
            bitmapimage.CacheOption = BitmapCacheOption.OnLoad;            //cache the image since we only need it once
            bitmapimage.EndInit();                                         //end the initalization

            //return the final image
            return(bitmapimage);
        }