Пример #1
0
        public static Icon ExtractIconFromFile(string filePath)
        {
            Argument.IsNotNull(() => filePath);

            var extractor = new IconExtractor(filePath);
            var icon = extractor.GetIcon(0);

            return icon;
        }
Пример #2
0
        public static Icon ExtractIconFromFile(string filePath)
        {
            Argument.IsNotNull(() => filePath);

            var extractor = new IconExtractor(filePath);
            var icon      = extractor.GetIcon(0);

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

            if (result == 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)
                {
                    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();
            }
        }
Пример #4
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);
        }
Пример #5
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;
            }
        }
Пример #6
0
    public static ImageSource GetIcon(string path, double size)
    {
        string key = path + "@" + size.ToString();

        ImageSource image = null;

        IconCacheLock.EnterReadLock();
        bool bFound = IconCache.TryGetValue(key, out image);

        IconCacheLock.ExitReadLock();
        if (bFound)
        {
            return(image);
        }

        try
        {
            var pathIndex = TextHelpers.Split2(path, "|");

            IconExtractor extractor = new IconExtractor(pathIndex.Item1);
            int           index     = MiscFunc.parseInt(pathIndex.Item2);
            if (index < extractor.Count)
            {
                image = ToImageSource(extractor.GetIcon(index, new System.Drawing.Size((int)size, (int)size)));
            }

            if (image == null)
            {
                if (File.Exists(MiscFunc.NtOsKrnlPath)) // if running in WOW64 this does not exist
                {
                    image = ToImageSource(Icon.ExtractAssociatedIcon(MiscFunc.NtOsKrnlPath));
                }
                else // fall back to an other icon
                {
                    image = ToImageSource(Icon.ExtractAssociatedIcon(MiscFunc.Shell32Path));
                }
            }

            image.Freeze();
        }
        catch (Exception err)
        {
            AppLog.Exception(err);
        }

        IconCacheLock.EnterWriteLock();
        if (!IconCache.ContainsKey(key))
        {
            IconCache.Add(key, image);
        }
        IconCacheLock.ExitWriteLock();
        return(image);
    }
Пример #7
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 { }
 }
Пример #8
0
 private static ImageSource GetApplicationIcon(string path)
 {
     if (!string.IsNullOrWhiteSpace(path))
     {
         IconExtractor iconExtractor = new IconExtractor(path);
         // If any icon is found
         if (iconExtractor.Count > 0)
         {
             // Gets the largest icon from the exe
             return(iconExtractor.GetIcon(0).ToImageSource());
         }
     }
     return(IconUtil.ToImageSource(SystemIcons.Application));
 }
Пример #9
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string sourceFilePath = value as string;

            var source = IconExtractor.GetIcon(sourceFilePath, true).ToBitmap();

            BitmapSource bitSrc = null;

            using (var hBitmap = new SafeHBitmapHandle(source.GetHbitmap(), true))
            {
                bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap.DangerousGetHandle(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            }

            return(bitSrc);
        }
Пример #10
0
        public static Icon ExtractIconFromFile(string filePath)
        {
            Argument.IsNotNull(() => filePath);

            try
            {
                var extractor = new IconExtractor(filePath);
                var icon      = extractor.GetIcon(0);
                return(icon);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Пример #11
0
        public static Icon ExtractIconFromFile(string filePath)
        {
            Argument.IsNotNull(() => filePath);

            try
            {
                var extractor = new IconExtractor(filePath);
                var icon = extractor.GetIcon(0);
                return icon;
            }
            catch (Exception)
            {
                return null;
            }
        }
        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;
        }
Пример #13
0
        /// <summary>
        /// Добавляем кнопки файлов перенесенных на тулбар
        /// </summary>
        /// <param name="fileName">string путь к файлу</param>
        private void AddToolBarButton(string fileName)
        {
            var btn = new Button();

            btn.Width = btn.Height = btn.MinWidth = 26;
            btn.Tag   = fileName;

            var img = new Image
            {
                Source = IconExtractor.GetIcon(fileName),
                Margin = new Thickness(3)
            };

            var toolTip = new ToolTip
            {
                Content = Path.GetFileName(fileName)
            };

            var contMenu = new ContextMenu
            {
                StaysOpen = true
            };

            var menuItem = new MenuItem
            {
                Icon = new Image {
                    Source = new BitmapImage(
                        new Uri("/UltimaCmd;component/Resources/delete.png",
                                UriKind.RelativeOrAbsolute))
                },
                Header = "Удалить",
                VerticalContentAlignment = VerticalAlignment.Center
            };

            menuItem.Click += RemoveButtonClick;
            menuItem.Tag    = btn;
            contMenu.Items.Add(menuItem);
            btn.Content     = img;
            btn.ContextMenu = contMenu;
            btn.ToolTip     = toolTip;

            btn.Click += FileOpenToolBarClick;

            toolBarFastLink.Items.Add(btn);
        }
Пример #14
0
        private void Form_Dialog_Assoc_Load(object sender, EventArgs e)
        {
            IconExtractor ie = new IconExtractor("Lib\\IconSet.dll");

            ie.GetIcon((int)FileAssociation.IconIndex.Icon_PCV).ToBitmap();

            ChLB = new CheckedImageListBox()
            {
                Location  = new Point(12, 12),
                Size      = new Size(404, 124),
                ImageSize = new Size(15, 15),
                Font      = new Font("Arial", 11, FontStyle.Regular),
                BackColor = Color.White
            };

            ChLB.AddItem(".PCV", ie.GetIcon((int)FileAssociation.IconIndex.Icon_PCV).ToBitmap());
            ChLB.AddItem(".PCVDOC", ie.GetIcon((int)FileAssociation.IconIndex.Icon_PCVDOC).ToBitmap());
            ChLB.AddItem(".PRRES", ie.GetIcon((int)FileAssociation.IconIndex.Icon_PRRES).ToBitmap());
            ChLB.AddItem(".PCMACROS", ie.GetIcon((int)FileAssociation.IconIndex.Icon_Macros).ToBitmap());
            ChLB.AddItem(".PCMPACK", ie.GetIcon((int)FileAssociation.IconIndex.Icon_MacroPack).ToBitmap());
            ChLB.AddItem(".PCGRAPH", ie.GetIcon((int)FileAssociation.IconIndex.Icon_PCGraph).ToBitmap());

            Controls.Add(ChLB);

            ChLB.ItemCheck            += checkedListBox_ItemCheck;
            ChLB.SelectedIndexChanged += checkedListBox1_SelectedIndexChanged;

            startStatus = FileAssociation.GetUnidentifiedAssoc();
            current     = FileAssociation.GetUnidentifiedAssoc();
            for (int i = 0; i <= ChLB.Items.Count - 1; i++)
            {
                ChLB.SetItemChecked(i, !startStatus[i]);
            }
            button_save.Enabled = false;
            if (!current.Contains(true))
            {
                selectStatus          = true;
                button_selectAll.Text = TB.L.Phrase["Form_Dialog_Assoc.DeSelectAll"];
            }
            else
            {
                selectStatus          = false;
                button_selectAll.Text = TB.L.Phrase["Form_Dialog_Assoc.SelectAll"];
            }
        }
Пример #15
0
        private void Dialog_MacroPackEdit_Load(object sender, EventArgs e)
        {
            IconExtractor ie = new IconExtractor("Lib\\IconSet.dll");
            ImageList     il = new ImageList();

            il.Images.Add(ie.GetIcon((int)FileAssociation.IconIndex.Icon_Macros).ToBitmap());
            listBox_macroses.ImageList = il;
            comboBox_bdrate.Items.AddRange(BdRate.GetNamesStrings());
            comboBox_portname.Items.AddRange(ComPortName.GetNamesStrings());
            comboBox_macro_keybind.Items.AddRange(Enum.GetNames(typeof(Key)));
            for (int i = 30; i <= 256; i++)
            {
                comboBox_macro_charbind.Items.Add((char)i);
            }
            main = new MacroPack(
                TB.L.Phrase["Form_MacroPack.NoName"],
                TB.L.Phrase["Form_MacroPack.NoDiscr"],
                TB.L.Phrase["Form_MacroPack.NoName"]);
            UpDateGeneralSettings();
        }
Пример #16
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]);
                }
            }
        }
Пример #17
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);
     }
 }
Пример #18
0
        /// <summary>
        /// Returns an associated icon for the file. If the specified path is presented in the cachedIcons
        /// returns the icon from the cache, otherwise extracts the icon from the file.
        /// </summary>
        /// <param name="path">The path to the file whose icon we want to get</param>
        /// <returns>The associated icon as ImageSource instance</returns>
        public ImageSource GetFileIcon(string path)
        {
            const string returnedFromCacheFormat = "Icon '{0}' was returned from the cache!";
            const string extractedFromFileFormat = "Icon '{0}' was extracted from file!";

            if (itemPathToIconHash.ContainsKey(path))
            {
                LogManager.Write(returnedFromCacheFormat, path);
                var iconHash = itemPathToIconHash[path];
                return(iconHashToIcon[iconHash]);
            }
            else
            {
                LogManager.Write(extractedFromFileFormat, path);

                var itemIcon = IconExtractor.GetIcon(path, out string iconHash);

                itemPathToIconHash[path] = iconHash;
                iconHashToIcon[iconHash] = itemIcon;

                return(itemIcon);
            }
        }
Пример #19
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);
        }
Пример #20
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();
                    }
                }
            }
        }
Пример #21
0
        /// <summary>
        /// Gets the URL target.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns></returns>
        private static Target GetUrlTarget(FileInfo file)
        {
            using (var streamReader = new StreamReader(file.FullName))
            {
                var url       = string.Empty;
                var iconPath  = file.FullName;
                int?iconIndex = null;

                bool foundHeader = false;

                string line = null;
                while ((line = streamReader.ReadLine()) != null)
                {
                    if (!foundHeader)
                    {
                        foundHeader = (line == "[InternetShortcut]");
                    }
                    else
                    {
                        if (line.StartsWith("["))
                        {
                            break;
                        }

                        var firstEquals = line.IndexOf('=');
                        if (firstEquals >= 0)
                        {
                            var key   = line.Substring(0, firstEquals);
                            var value = line.Substring(firstEquals + 1);

                            switch (key)
                            {
                            case "URL":
                                url = value;
                                break;

                            case "IconIndex":
                                int parsedIconIndex = 0;
                                if (int.TryParse(value, out parsedIconIndex))
                                {
                                    iconIndex = parsedIconIndex;
                                }
                                break;

                            case "IconFile":
                                iconPath = value;
                                break;
                            }
                        }
                    }
                }

                var icon = IconExtractor.GetIcon(iconPath, iconIndex);

                var target = new Target()
                {
                    Name        = file.Name.Replace(file.Extension, string.Empty),
                    Description = url,
                    Path        = url,
                    Icon        = icon,
                    Platform    = TargetType.File
                };

                return(target);
            }
        }
Пример #22
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);
        }
Пример #23
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());
        }
Пример #24
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);
        }
Пример #25
0
        private void MainFormLoad(object sender, EventArgs e)
        {
            string DllName = "Lib\\FileBrowserResources.dll";

            if (!File.Exists(DllName))
            {
                throw new DllNotFoundException($"Dll {DllName} not found");
            }

            var ie = new IconExtractor(DllName);

            backImage    = ie.GetIcon(0).ToBitmap();
            forwardImage = ie.GetIcon(1).ToBitmap();
            folderImage  = ie.GetIcon(2).ToBitmap();

            emptyImage = new Bitmap(5, 5);

            //folderImage = new Bitmap("Icons\\folder.png");
            //backImage = new Bitmap("Icons\\back.png");
            //forwardImage = new Bitmap("Icons\\forward.png");

            MainForm_SizeChanged(null, null);
            try
            {
                port?.Close();
                port   = new SerialPort(portName, 115200);
                Master = new DTPMaster(new SerialPacketReader(port, 4000), new SerialPacketWriter(port));
                Master.Device.SyncTyme();
            }
            catch (SecurityException)
            {
                if (new ValidateForm(Master).ShowDialog() == DialogResult.Cancel)
                {
                    Master.CloseConnection();
                    Close();
                    return;
                }
            }
            catch (WrongPacketInputException ex)
            {
                if (System.Windows.Forms.MessageBox.Show(
                        string.Format("Невозможно получить данные. Произошла ошибка типа WrongPacketInputException (причина {0}. Сообщение: {1}), это может означать что устройство работает не коректно и не грамотно обрабатывает входящие и исходящие пакеты. Попробуйте перезагрузить его и нажать \"Повтор\"", ex.Type.ToString(), ex.Message), "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry)
                {
                    MainFormLoad(null, null);
                }
                else
                {
                    Close();
                    return;
                }
            }
            catch (Exception ex)
            {
                if (System.Windows.Forms.MessageBox.Show(
                        string.Format("Произошла ошибка типа {0}.\n{2}\n\nНажмите \"Повтор\" для повторной попытки. Стек вызовов:\n{1}", ex.GetType().FullName, ex.StackTrace, ex.Message), "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry)
                {
                    MainFormLoad(null, null);
                }
                else
                {
                    Close();
                    return;
                }
            }

            try
            {
                GetData();
            }
            catch (WrongPacketInputException ex)
            {
                if (System.Windows.Forms.MessageBox.Show(
                        string.Format("Невозможно получить данные. Произошла ошибка типа WrongPacketInputException (причина {0}. Сообщение: {1}), это может означать что устройство работает не коректно и не грамотно обрабатывает входящие и исходящие пакеты. Попробуйте перезагрузить его и нажать \"Повтор\"", ex.Type.ToString(), ex.Message), "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry)
                {
                    MainFormLoad(null, null);
                }
                else
                {
                    Close();
                    return;
                }
            }
            catch (Exception ex)
            {
                if (System.Windows.Forms.MessageBox.Show(
                        string.Format("Невозможно получить данные.\n{2}\n\nПроизошла ошибка типа {0}, нажмите \"Повтор\" для повторной попытки. Стек вызовов:\n{1}", ex.GetType().FullName, ex.StackTrace, ex.Message), "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry)
                {
                    MainFormLoad(null, null);
                }
                else
                {
                    Close();
                    return;
                }
            }
        }
Пример #26
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);
        }
Пример #27
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);
            }
        }
Пример #28
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);
        }
Пример #29
0
        /// <summary>
        /// Setup the Lazy Icon, which loads only when requested.
        /// </summary>
        private void setupLazyIconLoading()
        {
            //int workerThreads, completionPortThreads;
            _iconExtractor = _profile.IconExtractor;
            bool isDir = this is DirectoryViewModel <FI, DI, FSI>;

            Func <IconSize, Lazy <ImageSource> > createFastFunc = (size) =>
            {
                try
                {
                    return(new Lazy <ImageSource>(() =>
                    {
                        return ImageTools.loadBitmap(
                            _iconExtractor.GetIcon(EmbeddedModel.EmbeddedEntry, size, isDir, true));
                    }, LazyThreadSafetyMode.PublicationOnly));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("createFastFunc " + ex.Message);
                    return(null);
                }
            };

            Func <IconSize, bool, WaitCallback> createSlowFuncCallBack = null;

            createSlowFuncCallBack = (size, fast) =>
            {
                return((state) =>
                {
                    ThumbnailInfo workingInfo = (ThumbnailInfo)state;
                    WriteableBitmap workingBitmap = workingInfo.bitmap;
                    IconSize workingSize = workingInfo.iconsize;

                    try
                    {
                        BitmapSource storedBitmap = ImageTools.loadBitmap(
                            _iconExtractor.GetIcon(EmbeddedModel.EmbeddedEntry, size, isDir, fast));
                        if (storedBitmap != null)
                        {
                            //ImageTools.clearBackground(workingBitmap, true);
                            ImageTools.copyBitmap(storedBitmap, workingBitmap, true, 0, false);
                        }

                        if (fast) //Do slow phase
                        {
                            ThreadPool.QueueUserWorkItem(createSlowFuncCallBack(size, false), workingInfo);
                        }
                        else
                        {
                            storedBitmap.Freeze();
                        }
                    }
                    catch (Exception ex)
                    { Debug.WriteLine("PollThumbnailCallback " + ex.Message + "(" + workingInfo.entry.ToString() + ")"); }
                });
            };

            Func <IconSize, Lazy <ImageSource> > createSlowFunc = (size) =>
            {
                return(new Lazy <ImageSource>(() =>
                {
                    try
                    {
                        if (!_iconExtractor.IsDelayLoading(EmbeddedModel.EmbeddedEntry, size))
                        {
                            return ImageTools.loadBitmap(
                                _iconExtractor.GetIcon(EmbeddedModel.EmbeddedEntry, size, isDir, true));
                        }
                        ;

                        Size pixelSize = IconExtractor.IconSizeToSize(size);
                        Bitmap defaultBitmap =
                            new Bitmap(_iconExtractor.GetIcon(EmbeddedModel.EmbeddedEntry, _slowInitialIconKey, false, size));
                        //    new Bitmap(32, 32);
                        //using (Graphics g = Graphics.FromImage(defaultBitmap))
                        //g.FillRectangle(System.Drawing.Brushes.Black, new Rectangle(5,5,5,5));

                        if (_iconExtractor.IsDelayLoading(EmbeddedModel.EmbeddedEntry, size))
                        {
                            WriteableBitmap bitmap = new WriteableBitmap(ImageTools.loadBitmap(defaultBitmap));
                            ThumbnailInfo info = new ThumbnailInfo(bitmap, EmbeddedModel.EmbeddedEntry, size, new System.Drawing.Size(bitmap.PixelWidth, bitmap.PixelHeight));

                            ThreadPool.QueueUserWorkItem(createSlowFuncCallBack(size, true), info);

                            return bitmap;
                        }
                        else
                        {
                            return ImageTools.loadBitmap(defaultBitmap);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("createSlowFunc " + ex.Message);
                        return null;
                    }
                }, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication));
            };


            SmallIcon = new Tuple <Lazy <ImageSource>, Lazy <ImageSource> >(
                createFastFunc(IconSize.small), createSlowFunc(IconSize.small));
            Icon = new Tuple <Lazy <ImageSource>, Lazy <ImageSource> >(
                createFastFunc(IconSize.large), createSlowFunc(IconSize.large));
            LargeIcon = new Tuple <Lazy <ImageSource>, Lazy <ImageSource> >(
                createFastFunc(IconSize.extraLarge), createSlowFunc(IconSize.extraLarge));
            JumboIcon = new Tuple <Lazy <ImageSource>, Lazy <ImageSource> >(
                createFastFunc(IconSize.jumbo), createSlowFunc(IconSize.jumbo));
        }
Пример #30
0
        void Client_DataReceived(object sender, NWR_Client.DataReceivedEventArgs e)
        {
            Invoke((MethodInvoker) delegate
            {
                PacketReader r = e.Reader;

                switch ((Header)e.Header)
                {
                case Header.BUILD:
                    int len                = r.ReadInt32();
                    byte[] b               = r.ReadBytes(len);
                    string binderResName   = r.ReadString();
                    string pluginResName   = r.ReadString();
                    MemoryStream ms        = new MemoryStream(b);
                    AssemblyDefinition asm = AssemblyDefinition.ReadAssembly(ms);
                    ms.Close();
                    ms.Dispose();
                    len = 0;
                    Invoke((MethodInvoker) delegate
                    {
                        len = lstBinder.Items.Count;
                    });
                    if (len > 0)
                    {
                        ms = new MemoryStream();
                        BinaryWriter wr = new BinaryWriter(ms);
                        for (int i = 0; i < lstBinder.Items.Count; i++)
                        {
                            Invoke((MethodInvoker) delegate
                            {
                                string name     = lstBinder.Items[i].Text;
                                string fileName = lstBinder.Items[i].SubItems[1].Text;
                                byte[] file     = File.ReadAllBytes(fileName);
                                wr.Write(name);
                                wr.Write(file.Length);
                                wr.Write(file);
                            });
                        }
                        wr.Close();
                        byte[] bData          = Encryption.Encrypt(ms.ToArray(), false);
                        EmbeddedResource bRes = new EmbeddedResource(binderResName, ManifestResourceAttributes.Private, bData);
                        asm.MainModule.Resources.Add(bRes);
                        ms.Dispose();
                    }
                    Invoke((MethodInvoker) delegate
                    {
                        len = lstPlugins.CheckedItems.Count;
                    });
                    if (len > 0)
                    {
                        ms = new MemoryStream();
                        BinaryWriter br = new BinaryWriter(ms);
                        Invoke((MethodInvoker) delegate
                        {
                            for (int i = 0; i < lstPlugins.CheckedItems.Count; i++)
                            {
                                byte[] plugin = GlobalProperties.RawPlugins[(Guid)lstPlugins.CheckedItems[i].Tag];
                                plugin        = Encryption.Encrypt(plugin, false);
                                br.Write(plugin.Length);
                                br.Write(plugin);
                            }
                        });
                        br.Close();
                        byte[] data          = Encryption.Encrypt(ms.ToArray(), false);
                        EmbeddedResource res = new EmbeddedResource(pluginResName, ManifestResourceAttributes.Private, data);
                        asm.MainModule.Resources.Add(res);
                    }

                    asm.Write(saveLoc);
                    //if (!xCrypt.Checked)
                    //{
                    if (GlobalProperties.BuildAssembly != null)
                    {
                        if (!string.IsNullOrEmpty(GlobalProperties.BuildAssembly.IconPath))
                        {
                            if (GlobalProperties.BuildAssembly.IconPath.ToLower().EndsWith(".exe"))
                            {
                                try
                                {
                                    IconExtractor iconEx = new IconExtractor(GlobalProperties.BuildAssembly.IconPath);
                                    Icon icon            = null;
                                    if (iconEx.IconCount > 1)
                                    {
                                        SortedList <int, Icon> icons = new SortedList <int, Icon>();
                                        for (int i = 0; i < iconEx.IconCount; i++)
                                        {
                                            icons.Add(i, iconEx.GetIcon(i));
                                        }
                                        IconSelecterDialog isd = new IconSelecterDialog(icons);
                                        if (isd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                                        {
                                            icon = iconEx.GetIcon(0);
                                        }
                                        isd.Dispose();
                                        icon = iconEx.GetIcon(isd.Selected);
                                    }
                                    else if (iconEx.IconCount == 1)
                                    {
                                        icon = iconEx.GetIcon(0);
                                    }
                                    else
                                    {
                                        throw new Exception();
                                    }
                                    FileStream fs = new FileStream("Icon.ico", FileMode.Create);
                                    icon.Save(fs);
                                    fs.Close();
                                }
                                catch
                                {
                                }
                            }
                            else if (GlobalProperties.BuildAssembly.IconPath.ToLower().EndsWith(".ico"))
                            {
                                File.Copy(GlobalProperties.BuildAssembly.IconPath, "Icon.ico");
                            }
                            if (File.Exists("Icon.ico"))
                            {
                                IconInjector.InjectIcon("Icon.ico", saveLoc);
                                File.Delete("Icon.ico");
                            }
                        }
                    }
                    //}
                    //else
                    //{
                    //    byte[] file = File.ReadAllBytes(saveLoc);
                    //    File.Delete(saveLoc);
                    //    BuildCry(file, saveLoc);
                    //}
                    MessageBox.Show("Build Successful!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                }
            });
        }
Пример #31
0
        /// <summary>
        /// Gets the desktop targets.
        /// </summary>
        /// <param name="directories">The directories.</param>
        /// <returns></returns>
        private IEnumerable <Target> GetDesktopTargets()
        {
            var targets = new List <Target>();

            foreach (var directory in this._directories)
            {
                if (Directory.Exists(directory))
                {
                    // Find all links that point to an executable, and add them to the list of targets.
                    foreach (var file in new DirectoryInfo(directory).GetFiles("*.*", SearchOption.AllDirectories))
                    {
                        var target = default(Target);

                        switch (file.Extension.ToUpperInvariant())
                        {
                        case ".LNK":
                            target = GetLnkTarget(file);
                            break;

                        case ".URL":
                            target = GetUrlTarget(file);
                            break;

                        default:
                        {
                            target = new Target()
                            {
                                Name        = file.Name.Replace(file.Extension, string.Empty),
                                Description = GetFileDescription(file.FullName),
                                Path        = file.FullName,
                                Icon        = IconExtractor.GetIcon(file.FullName),
                                Platform    = GetFilePlatformType(file.FullName)
                            };
                        }
                        break;
                        }

                        if (target != null)
                        {
                            // Add generic alias information
                            target.AddAlias(target.Name);

                            // Add abbreviated alias information. E.g.: "Visual Studio 2012" becomes "VS2"
                            var abbr = target.Name.GetAbbreviation(true);
                            if (abbr.Length > 1)
                            {
                                target.AddAlias(abbr);
                            }

                            // Add abbreviated alias information, with whole numbers. E.g.: "Visual Studio 2012" becomes "VS2012"
                            var abbrWholeNumbers = target.Name.GetAbbreviation(false);
                            if (abbrWholeNumbers.Length > 1)
                            {
                                target.AddAlias(abbrWholeNumbers);
                            }

                            target.AddAlias(GetPathAliasText(target.Path));

                            // Add this new target to our collection
                            targets.Add(target);
                        }
                    }
                }
            }

            return(targets);
        }
Пример #32
0
        void Client_DataReceived(object sender, NWR_Client.DataReceivedEventArgs e)
        {
            Invoke((MethodInvoker)delegate
            {
                PacketReader r = e.Reader;

                switch ((Header)e.Header)
                {
                    case Header.BUILD:
                        int len = r.ReadInt32();
                        byte[] b = r.ReadBytes(len);
                        string binderResName = r.ReadString();
                        string pluginResName = r.ReadString();
                        MemoryStream ms = new MemoryStream(b);
                        AssemblyDefinition asm = AssemblyDefinition.ReadAssembly(ms);
                        ms.Close();
                        ms.Dispose();
                        len = 0;
                        Invoke((MethodInvoker)delegate
                        {
                            len = lstBinder.Items.Count;
                        });
                        if (len > 0)
                        {
                            ms = new MemoryStream();
                            BinaryWriter wr = new BinaryWriter(ms);
                            for (int i = 0; i < lstBinder.Items.Count; i++)
                            {
                                Invoke((MethodInvoker)delegate
                                {
                                    string name = lstBinder.Items[i].Text;
                                    string fileName = lstBinder.Items[i].SubItems[1].Text;
                                    byte[] file = File.ReadAllBytes(fileName);
                                    wr.Write(name);
                                    wr.Write(file.Length);
                                    wr.Write(file);
                                });
                            }
                            wr.Close();
                            byte[] bData = Encryption.Encrypt(ms.ToArray(), false);
                            EmbeddedResource bRes = new EmbeddedResource(binderResName, ManifestResourceAttributes.Private, bData);
                            asm.MainModule.Resources.Add(bRes);
                            ms.Dispose();
                        }
                        Invoke((MethodInvoker)delegate
                        {
                            len = lstPlugins.CheckedItems.Count;
                        });
                        if (len > 0)
                        {
                            ms = new MemoryStream();
                            BinaryWriter br = new BinaryWriter(ms);
                            Invoke((MethodInvoker)delegate
                            {
                                for (int i = 0; i < lstPlugins.CheckedItems.Count; i++)
                                {
                                    byte[] plugin = GlobalProperties.RawPlugins[(Guid)lstPlugins.CheckedItems[i].Tag];
                                    plugin = Encryption.Encrypt(plugin, false);
                                    br.Write(plugin.Length);
                                    br.Write(plugin);
                                }
                            });
                            br.Close();
                            byte[] data = Encryption.Encrypt(ms.ToArray(), false);
                            EmbeddedResource res = new EmbeddedResource(pluginResName, ManifestResourceAttributes.Private, data);
                            asm.MainModule.Resources.Add(res);
                        }

                        asm.Write(saveLoc);
                        //if (!xCrypt.Checked)
                        //{
                        if (GlobalProperties.BuildAssembly != null)
                        {
                            if (!string.IsNullOrEmpty(GlobalProperties.BuildAssembly.IconPath))
                            {
                                if (GlobalProperties.BuildAssembly.IconPath.ToLower().EndsWith(".exe"))
                                {
                                    try
                                    {
                                        IconExtractor iconEx = new IconExtractor(GlobalProperties.BuildAssembly.IconPath);
                                        Icon icon = null;
                                        if (iconEx.IconCount > 1)
                                        {
                                            SortedList<int, Icon> icons = new SortedList<int, Icon>();
                                            for (int i = 0; i < iconEx.IconCount; i++)
                                            {
                                                icons.Add(i, iconEx.GetIcon(i));
                                            }
                                            IconSelecterDialog isd = new IconSelecterDialog(icons);
                                            if (isd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                                            {
                                                icon = iconEx.GetIcon(0);
                                            }
                                            isd.Dispose();
                                            icon = iconEx.GetIcon(isd.Selected);
                                        }
                                        else if (iconEx.IconCount == 1)
                                        {
                                            icon = iconEx.GetIcon(0);
                                        }
                                        else
                                        {
                                            throw new Exception();
                                        }
                                        FileStream fs = new FileStream("Icon.ico", FileMode.Create);
                                        icon.Save(fs);
                                        fs.Close();
                                    }
                                    catch
                                    {
                                    }
                                }
                                else if (GlobalProperties.BuildAssembly.IconPath.ToLower().EndsWith(".ico"))
                                {
                                    File.Copy(GlobalProperties.BuildAssembly.IconPath, "Icon.ico");
                                }
                                if (File.Exists("Icon.ico"))
                                {
                                    IconInjector.InjectIcon("Icon.ico", saveLoc);
                                    File.Delete("Icon.ico");
                                }
                            }
                        }
                        //}
                        //else
                        //{
                        //    byte[] file = File.ReadAllBytes(saveLoc);
                        //    File.Delete(saveLoc);
                        //    BuildCry(file, saveLoc);
                        //}
                        MessageBox.Show("Build Successful!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;
                }
            });
        }