Esempio n. 1
0
 private string kind(string extension)
 {
     Shell32.SHFILEINFO shinfo = new Shell32.SHFILEINFO();
     IntPtr hSuccess = Shell32.SHGetFileInfo(extension, 0, ref shinfo, (uint) Marshal.SizeOf(shinfo),
                                             Shell32.SHGFI_TYPENAME | Shell32.SHGFI_USEFILEATTRIBUTES);
     if (hSuccess != IntPtr.Zero)
     {
         return Convert.ToString(shinfo.szTypeName.Trim());
     }
     return null;
 }
Esempio n. 2
0
        public static bool IsConsoleSubsystem(string executablePath)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                // Under UNIX all applications are effectively console.
                return(true);
            }

            var info           = new Shell32.SHFILEINFO();
            var executableType = (uint)Shell32.SHGetFileInfo(executablePath, 0u, ref info, (uint)Marshal.SizeOf(info), Shell32.SHGFI_EXETYPE);

            return(executableType == Shell32.MZ || executableType == Shell32.PE);
        }
Esempio n. 3
0
        public static System.Drawing.Icon GetFileIcon(string name)
        {
            Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
            uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES | Shell32.SHGFI_SMALLICON;

            Shell32.SHGetFileInfo(name,
                                  Shell32.FILE_ATTRIBUTE_NORMAL,
                                  ref shfi,
                                  (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                  flags);


            System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
            User32.DestroyIcon(shfi.hIcon);
            return(icon);
        }
        private static Icon CloneIcon(Shell32.SHFILEINFO fileInfo)
        {
            Icon icon = default;

            try
            {
                using (var temp = Icon.FromHandle(fileInfo.hIcon))
                {
                    icon = (Icon)temp.Clone();
                }
            }
            catch { }
            finally
            {
                User32.DestroyIcon(fileInfo.hIcon);
            }
            return(icon);
        }
        private static Icon GetFileIconFromName(string filename, bool isFolder, IconSize size, bool linkOverlay)
        {
            Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
            uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

            if (linkOverlay)
            {
                flags |= Shell32.SHGFI_LINKOVERLAY;
            }

            if (IconSize.Small == size)
            {
                flags |= Shell32.SHGFI_SMALLICON;
            }
            else
            {
                flags |= Shell32.SHGFI_LARGEICON;
            }

            uint fileAttributes;

            if (isFolder)
            {
                fileAttributes = Shell32.FILE_ATTRIBUTE_DIRECTORY;
            }
            else
            {
                fileAttributes = Shell32.FILE_ATTRIBUTE_NORMAL;
            }

            IntPtr hSuccess = Shell32.SHGetFileInfo(
                filename, fileAttributes,
                ref shfi, (uint)Marshal.SizeOf(shfi),
                flags);

            if (hSuccess == IntPtr.Zero)
            {
                return(null);
            }

            return(CloneIcon(shfi));
        }
Esempio n. 6
0
        /// <summary>
        /// Used to access system folder icons.
        /// </summary>
        /// <param name="size">Specify large or small icons.</param>
        /// <param name="folderType">Specify open or closed FolderType.</param>
        /// <returns>System.Drawing.Icon</returns>
        public static System.Drawing.Icon GetFolderIcon(SystemIconSize size, FolderType folderType)
        {
            // Need to add size check, although errors generated at present!
            uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

            if (FolderType.Open == folderType)
            {
                flags += Shell32.SHGFI_OPENICON;
            }

            if (SystemIconSize.Small == size)
            {
                flags += Shell32.SHGFI_SMALLICON;
            }
            else
            {
                flags += Shell32.SHGFI_LARGEICON;
            }

            // Get the folder icon
            Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
            Shell32.SHGetFileInfo("dummy",                // Windows 7 needs a string passed to this regardless. Previous versions of windows could handle null
                                  Shell32.FILE_ATTRIBUTE_DIRECTORY,
                                  ref shfi,
                                  (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                  flags);

            if (shfi.hIcon != IntPtr.Zero)
            {
                System.Drawing.Icon.FromHandle(shfi.hIcon);                     // Load the icon from an HICON handle

                // Now clone the icon, so that it can be successfully stored in an ImageList
                System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

                User32.DestroyIcon(shfi.hIcon);                         // Cleanup
                return(icon);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 7
0
        public static System.Drawing.Icon GetFileIcon(string name, IconSize size, bool linkOverlay)
        {
            Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
            uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

            if (true == linkOverlay)
            {
                flags += Shell32.SHGFI_LINKOVERLAY;
            }


            /* Check the size specified for return. */
            if (IconSize.Small == size)
            {
                flags += Shell32.SHGFI_SMALLICON;                  // include the small icon flag
            }
            else
            {
                flags += Shell32.SHGFI_LARGEICON;                   // include the large icon flag
            }

            Shell32.SHGetFileInfo(name,
                                  Shell32.FILE_ATTRIBUTE_NORMAL,
                                  ref shfi,
                                  (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                  flags);


            // Copy (clone) the returned icon to a new object, thus allowing us
            // to call DestroyIcon immediately
            if (shfi.hIcon == IntPtr.Zero)
            {
                return(null);
            }
            else
            {
                System.Drawing.Icon icon = (System.Drawing.Icon)
                                           System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
                User32.DestroyIcon(shfi.hIcon);                   // Cleanup
                return(icon);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Returns an icon for a given file - indicated by the name parameter.
        /// </summary>
        /// <param name="name">Pathname for file.</param>
        /// <returns>System.Drawing.Icon</returns>
        private Icon GetFileIcon(string name)
        {
            try{
                Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
                uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES | Shell32.SHGFI_SMALLICON;

                Shell32.SHGetFileInfo(name,
                                      Shell32.FILE_ATTRIBUTE_NORMAL,
                                      ref shfi,
                                      (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                      flags);

                // Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
                System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
                User32.DestroyIcon(shfi.hIcon);                         // Cleanup
                return(icon);
            }
            catch {
                return(ResManager.GetIcon("attach"));
            }
        }
Esempio n. 9
0
        public static (string icon, bool isCustom) GetFileOverlayIcon(string path)
        {
            var shfi = new Shell32.SHFILEINFO();
            var ret  = Shell32.SHGetFileInfo(path, 0, ref shfi, Shell32.SHFILEINFO.Size, Shell32.SHGFI.SHGFI_OVERLAYINDEX | Shell32.SHGFI.SHGFI_ICON | Shell32.SHGFI.SHGFI_SYSICONINDEX | Shell32.SHGFI.SHGFI_ICONLOCATION);

            if (ret == IntPtr.Zero)
            {
                return(null, false);
            }

            bool isCustom = !shfi.szDisplayName.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.Windows));

            User32.DestroyIcon(shfi.hIcon);
            Shell32.SHGetImageList(Shell32.SHIL.SHIL_LARGE, typeof(ComCtl32.IImageList).GUID, out var tmp);
            using var imageList = ComCtl32.SafeHIMAGELIST.FromIImageList(tmp);
            if (imageList.IsNull || imageList.IsInvalid)
            {
                return(null, isCustom);
            }

            var overlay_idx = shfi.iIcon >> 24;

            //var icon_idx = shfi.iIcon & 0xFFFFFF;
            if (overlay_idx == 0)
            {
                return(null, isCustom);
            }

            var overlay_image = imageList.Interface.GetOverlayImage(overlay_idx);

            using var hIcon = imageList.Interface.GetIcon(overlay_image, ComCtl32.IMAGELISTDRAWFLAGS.ILD_TRANSPARENT);
            if (hIcon.IsNull || hIcon.IsInvalid)
            {
                return(null, isCustom);
            }

            using var image = hIcon.ToIcon().ToBitmap();
            byte[] bitmapData = (byte[])new ImageConverter().ConvertTo(image, typeof(byte[]));
            return(Convert.ToBase64String(bitmapData, 0, bitmapData.Length), isCustom);
        }
Esempio n. 10
0
            /// <summary>
            /// Gets item's display information</summary>
            /// <param name="item">Item being displayed</param>
            /// <param name="info">Item info, to fill out</param>
            public virtual void GetInfo(object item, ItemInfo info)
            {
                Uri resourceUri = ResourceLister.GetUriFromTag(item);

                if (resourceUri != null)
                {
                    FileInfo fileInfo = new FileInfo(resourceUri.LocalPath);

                    info.Label      = fileInfo.Name;
                    info.ImageIndex = info.GetImageList().Images.IndexOfKey(Sce.Atf.Resources.ResourceImage);

                    Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
                    uint flags = Shell32.SHGFI_TYPENAME | Shell32.SHGFI_USEFILEATTRIBUTES;
                    Shell32.SHGetFileInfo(fileInfo.FullName,
                                          Shell32.FILE_ATTRIBUTE_NORMAL,
                                          ref shfi,
                                          (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                          flags);

                    string   typeName = shfi.szTypeName;
                    long     length;
                    DateTime lastWriteTime;
                    try
                    {
                        length        = fileInfo.Length;
                        lastWriteTime = fileInfo.LastWriteTime;
                    }
                    catch (IOException)
                    {
                        length        = 0;
                        lastWriteTime = new DateTime();
                    }

                    info.Properties = new object[] {
                        length,
                        typeName,
                        lastWriteTime
                    };
                }
            }
Esempio n. 11
0
		public static System.Drawing.Icon GetFileIcon(string name, IconSize size, bool linkOverlay)
		{
			Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
			uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;
    
			if (true == linkOverlay) flags += Shell32.SHGFI_LINKOVERLAY;

			
			/* Check the size specified for return. */
			if (IconSize.Small == size)
			{
				flags += Shell32.SHGFI_SMALLICON ; // include the small icon flag
			} 
			else 
			{
				flags += Shell32.SHGFI_LARGEICON ;  // include the large icon flag
			}
    
			Shell32.SHGetFileInfo( name, 
				Shell32.FILE_ATTRIBUTE_NORMAL, 
				ref shfi, 
				(uint) System.Runtime.InteropServices.Marshal.SizeOf(shfi), 
				flags );


			// Copy (clone) the returned icon to a new object, thus allowing us 
			// to call DestroyIcon immediately
			if (shfi.hIcon == IntPtr.Zero)
			{
				return null;
			}
			else
			{
				System.Drawing.Icon icon = (System.Drawing.Icon)
					System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
				User32.DestroyIcon( shfi.hIcon ); // Cleanup
				return icon;
			}
		}	
Esempio n. 12
0
    /// <summary>
    /// Adds images of the file extensions to the ImageLists
    /// </summary>
    /// <param name="itemExtension">File extension ; e.g. .exe, .dll, .png</param>
    /// <param name="smallIconImageList">Small icon ImageList - 16x16 icon size</param>
    /// <param name="largeIconImageList">Large icon ImageList - 48x48 icon size</param>
    public void AddFileIcons(String itemExtension, ImageList smallIconImageList, ImageList largeIconImageList = null)
    {
        OSIcon.WinAPI.Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
        Icon smallIcon = IconReader.GetFileIcon(itemExtension, IconReader.IconSize.Small, false, ref shfi);
        Icon largeIcon = IconReader.GetFileIcon(itemExtension, IconReader.IconSize.ExtraLarge, false, ref shfi);

        if (largeIconImageList != null)
        {
            if (!(smallIconImageList.Images.ContainsKey(itemExtension) && largeIconImageList.Images.ContainsKey(itemExtension)))
            {
                smallIconImageList.Images.Add(itemExtension, smallIcon.ToBitmap());
                largeIconImageList.Images.Add(itemExtension, largeIcon.ToBitmap());
            }
        }
        else
        {
            if (!(smallIconImageList.Images.ContainsKey(itemExtension) && largeIconImageList.Images.ContainsKey(itemExtension)))
            {
                smallIconImageList.Images.Add(itemExtension, smallIcon.ToBitmap());
            }
        }
    }
        private static Icon GetFileIconFromExecutable(string filename, IconSize size)
        {
            Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
            uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

            if (IconSize.Small == size)
            {
                flags += Shell32.SHGFI_SMALLICON;
            }
            else
            {
                flags += Shell32.SHGFI_LARGEICON;
            }
            IntPtr hSuccess = Shell32.SHGetFileInfo(filename, Shell32.FILE_ATTRIBUTE_NORMAL, ref shfi,
                                                    (uint)Marshal.SizeOf(shfi), flags);

            if (hSuccess == IntPtr.Zero)
            {
                return(null);
            }

            return(CloneIcon(shfi));
        }
Esempio n. 14
0
        public void AddFile(TreeListViewItem node, string fsFullPath)
        {
            try
            {
                FileInfo diChild = new FileInfo(fsFullPath);
                string   strExt  = diChild.Extension.ToLower();
                if (strExt == ".exe")
                {
                    strExt = diChild.FullName.ToLower();
                }

                Shell32.SHFILEINFO shFileInfo = new Shell32.SHFILEINFO();
                Icon SmallIcon = Apq.Windows.Forms.IconChache.GetFileSystemIcon(diChild.FullName, ref shFileInfo);

                TreeListViewItem ndChild = new TreeListViewItem(diChild.Name);
                node.Items.Add(ndChild);
                if (node.CheckStatus != CheckState.Indeterminate)
                {
                    ndChild.Checked = node.Checked;
                }
                ndChild.ImageIndex = _imgList.Images.IndexOfKey(strExt);
                ndChild.SubItems.Add(diChild.Length.ToString("n0"));
                if (strExt.Contains("\\"))
                {
                    strExt = "应用程序";
                }
                ndChild.SubItems.Add(shFileInfo.szTypeName);
                ndChild.SubItems.Add(diChild.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"));
                ndChild.SubItems.Add(diChild.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"));

                ndChild.SubItems.Add(diChild.Name);
                ndChild.SubItems.Add("-1");
                ndChild.SubItems.Add("3");                //类型{1:Drive,2:Folder,3:File}
            }
            catch { }
        }
Esempio n. 15
0
        /// <summary>
        /// Used to access system folder icons.
        /// </summary>
        /// <param name="size">Specify large or small icons.</param>
        /// <param name="folderType">Specify open or closed FolderType.</param>
        /// <returns>System.Drawing.Icon</returns>
        public static System.Drawing.Icon GetFolderIcon(IconSize size, FolderType folderType)
        {
            // Need to add size check, although errors generated at present!
            uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

            if (FolderType.Open == folderType)
            {
                flags |= Shell32.SHGFI_OPENICON;
            }

            if (IconSize.Small == size)
            {
                flags |= Shell32.SHGFI_SMALLICON;
            }
            else
            {
                flags |= Shell32.SHGFI_LARGEICON;
            }

            // Get the folder icon
            var shfi = new Shell32.SHFILEINFO();

            Shell32.SHGetFileInfo(null,
                                  Shell32.FILE_ATTRIBUTE_DIRECTORY,
                                  ref shfi,
                                  (uint)Marshal.SizeOf(shfi),
                                  flags);

            System.Drawing.Icon.FromHandle(shfi.hIcon);                 // Load the icon from an HICON handle

            // Now clone the icon, so that it can be successfully stored in an ImageList
            var icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

            User32.DestroyIcon(shfi.hIcon);                             // Cleanup
            return(icon);
        }
Esempio n. 16
0
        public static System.Drawing.Icon GetFileIcon(string name, IconSize size, bool linkOverlay)
        {
            System.Drawing.Icon icon = System.Drawing.SystemIcons.Shield;
            try
            {
                Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
                uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

                if (true == linkOverlay)
                {
                    flags += Shell32.SHGFI_LINKOVERLAY;
                }

                /* Check the size specified for return. */
                if (IconSize.Small == size)
                {
                    flags += Shell32.SHGFI_SMALLICON;
                }
                else
                {
                    flags += Shell32.SHGFI_LARGEICON;
                }

                Shell32.SHGetFileInfo(name,
                                      Shell32.FILE_ATTRIBUTE_NORMAL,
                                      ref shfi,
                                      (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                      flags);

                // Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
                icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
                User32.DestroyIcon(shfi.hIcon);         // Cleanup
            }
            catch (Exception ex) { }
            return(icon);
        }
Esempio n. 17
0
        private Icon GetFolderIcon(IconSize size = IconSize.small, FolderType folderType = FolderType.Closed)
        {
            // Need to add size check, although errors generated at present!
            uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

            if (FolderType.Open == folderType)
            {
                flags += Shell32.SHGFI_OPENICON;
            }

            if (IconSize.small == size)
            {
                flags += Shell32.SHGFI_SMALLICON;
            }
            else
            {
                flags += Shell32.SHGFI_LARGEICON;
            }

            // Get the folder icon
            Shell32.SHFILEINFO shfi     = new Shell32.SHFILEINFO();
            IntPtr             hSuccess = Shell32.SHGetFileInfo("_unknown", Shell32.FILE_ATTRIBUTE_DIRECTORY, ref shfi,
                                                                (uint)Marshal.SizeOf(shfi), flags);

            if (hSuccess != IntPtr.Zero)
            {
                Icon.FromHandle(shfi.hIcon); // Load the icon from an HICON handle

                // Now clone the icon, so that it can be successfully stored in an ImageList
                Icon icon = (Icon)Icon.FromHandle(shfi.hIcon).Clone();

                User32.DestroyIcon(shfi.hIcon); // Cleanup
                return(icon);
            }
            return(null);
        }
Esempio n. 18
0
            /// <summary>
            /// Fills in or modifies the given display info for the item
            /// </summary>
            /// <param name="item">Item</param>
            /// <param name="info">Display info to update</param>
            public void GetInfo(object item, ItemInfo info)
            {
                IResource asset = item as IResource;

                if (asset != null)
                {
                    FileInfo fileInfo = new FileInfo(asset.Uri.LocalPath);
                    info.Label          = fileInfo.Name;
                    info.ImageIndex     = 0; //info.ImageList.Images.IndexOfKey(item.Indicator);
                    info.AllowLabelEdit = false;

                    Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
                    uint flags = Shell32.SHGFI_TYPENAME | Shell32.SHGFI_USEFILEATTRIBUTES;
                    Shell32.SHGetFileInfo(fileInfo.FullName,
                                          Shell32.FILE_ATTRIBUTE_NORMAL,
                                          ref shfi,
                                          (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                          flags);

                    string   typeName = shfi.szTypeName;
                    long     length;
                    DateTime lastWriteTime;
                    try
                    {
                        length        = fileInfo.Length;
                        lastWriteTime = fileInfo.LastWriteTime;
                    }
                    catch (IOException)
                    {
                        length        = 0;
                        lastWriteTime = new DateTime();
                    }

                    info.Properties = new object[] { fileInfo.Name, length, typeName, lastWriteTime };
                }
            }
Esempio n. 19
0
        private void FrmInfo_Load(object sender, EventArgs e)
        {
            SHFILEINFO shfi = new SHFILEINFO();
            SHGetFileInfo(Gib.rbfile, (uint)0x80, ref shfi, 16640, (uint)(0x100 | 0x400)); //获取文件的图标及类型
            Icon ico = (Icon)Icon.FromHandle(shfi.hIcon).Clone();
            Image img = Image.FromHbitmap(ico.ToBitmap().GetHbitmap());
            filepic.Image = GetNewImage(img, 45, 45);

            filename.Text = Path.GetFileName(Gib.rbfile);

            filetype.Text = GetTypeName(Gib.rbfile);

            filepath.Text = Gib.rbfile;

            if (File.Exists(Gib.rbfile))
            {
                FileInfo fi = new FileInfo(Gib.rbfile);
                fl = fi.Length;
                reffs();

                filecreatdate.Text = File.GetCreationTime(Gib.rbfile).ToString();

                filechangedate.Text = File.GetLastWriteTime(Gib.rbfile).ToString();
            }
            else
            {
                foldersize(Gib.rbfile);
                reffs();

                filecreatdate.Text = Directory.GetCreationTime(Gib.rbfile).ToString();

                filechangedate.Text = Directory.GetLastWriteTime(Gib.rbfile).ToString();
            }
        }
Esempio n. 20
0
 public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref Shell32.SHFILEINFO psfi, uint cbFileInfo, uint uFlags);
Esempio n. 21
0
        /// <summary>
        /// Internal add a icon to class
        /// FOLDERS ONLY!!!!!!
        /// </summary>
        /// <param name="path">Icon Path on filesystem, or extension</param>
        /// <param name="iconSize">Icon Size</param>
        /// <param name="iconProp">Icon Properties to assign to list</param>
        /// <param name="folder">Folder type (open or closed)</param>
        private void Add(string path, IconReader.IconSize iconSize, IconProperties iconProp, IconReader.FolderType folder)
        {
            iconProp.IconsIndex[iconSize] = -1;
            iconProp.IconsInfo[iconSize] = new Shell32.SHFILEINFO();
            Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
            iconProp.Icons[iconSize] = IconReader.GetFolderIcon(iconSize, folder, ref shfi);

            iconProp.IconsInfo[iconSize] = shfi;
            if(IImageList[iconSize] != null)
            {
                iconProp.IconsIndex[iconSize] = IImageList[iconSize].Images.Count;
                IImageList[iconSize].Images.Add(path, iconProp.Icons[iconSize]);
            }
        }
Esempio n. 22
0
        private static async Task parseArguments(AppServiceRequestReceivedEventArgs args, AppServiceDeferral messageDeferral, string arguments, ApplicationDataContainer localSettings)
        {
            switch (arguments)
            {
            case "Terminate":
                // Exit fulltrust process (UWP is closed or suspended)
                appServiceExit.Set();
                messageDeferral.Complete();
                break;

            case "RecycleBin":
                var binAction = (string)args.Request.Message["action"];
                await parseRecycleBinAction(args, binAction);

                break;

            case "StartupTasks":
                // Check QuickLook Availability
                QuickLook.CheckQuickLookAvailability(localSettings);
                break;

            case "ToggleQuickLook":
                var path = (string)args.Request.Message["path"];
                QuickLook.ToggleQuickLook(path);
                break;

            case "ShellCommand":
                // Kill the process. This is a BRUTAL WAY to kill a process.
#if DEBUG
                // In debug mode this kills this process too??
#else
                var pid = (int)args.Request.Message["pid"];
                Process.GetProcessById(pid).Kill();
#endif

                Process process = new Process();
                process.StartInfo.UseShellExecute = true;
                process.StartInfo.FileName        = "explorer.exe";
                process.StartInfo.CreateNoWindow  = false;
                process.StartInfo.Arguments       = (string)args.Request.Message["ShellCommand"];
                process.Start();
                break;

            case "LoadContextMenu":
                var contextMenuResponse        = new ValueSet();
                var loadThreadWithMessageQueue = new Win32API.ThreadWithMessageQueue <ValueSet>(HandleMenuMessage);
                var cMenuLoad = await loadThreadWithMessageQueue.PostMessage <Win32API.ContextMenu>(args.Request.Message);

                contextMenuResponse.Add("Handle", handleTable.AddValue(loadThreadWithMessageQueue));
                contextMenuResponse.Add("ContextMenu", JsonConvert.SerializeObject(cMenuLoad));
                await args.Request.SendResponseAsync(contextMenuResponse);

                break;

            case "ExecAndCloseContextMenu":
                var menuKey = (string)args.Request.Message["Handle"];
                var execThreadWithMessageQueue = handleTable.GetValue <Win32API.ThreadWithMessageQueue <ValueSet> >(menuKey);
                if (execThreadWithMessageQueue != null)
                {
                    await execThreadWithMessageQueue.PostMessage(args.Request.Message);
                }
                // The following line is needed to cleanup resources when menu is closed.
                // Unfortunately if you uncomment it some menu items will randomly stop working.
                // Resource cleanup is currently done on app closing,
                // if we find a solution for the issue above, we should cleanup as soon as a menu is closed.
                //handleTable.RemoveValue(menuKey);
                break;

            case "InvokeVerb":
                var filePath = (string)args.Request.Message["FilePath"];
                var split    = filePath.Split('|').Where(x => !string.IsNullOrWhiteSpace(x));
                using (var cMenu = Win32API.ContextMenu.GetContextMenuForFiles(split.ToArray(), Shell32.CMF.CMF_DEFAULTONLY))
                {
                    cMenu?.InvokeVerb((string)args.Request.Message["Verb"]);
                }
                break;

            case "Bitlocker":
                var bitlockerAction = (string)args.Request.Message["action"];
                if (bitlockerAction == "Unlock")
                {
                    var drive    = (string)args.Request.Message["drive"];
                    var password = (string)args.Request.Message["password"];
                    Win32API.UnlockBitlockerDrive(drive, password);
                    await args.Request.SendResponseAsync(new ValueSet()
                    {
                        { "Bitlocker", "Unlock" }
                    });
                }
                break;

            case "FileOperation":
                await parseFileOperation(args);

                break;

            case "CheckCustomIcon":
                var folderPath    = (string)args.Request.Message["folderPath"];
                var shfi          = new Shell32.SHFILEINFO();
                var ret           = Shell32.SHGetFileInfo(folderPath, 0, ref shfi, Shell32.SHFILEINFO.Size, Shell32.SHGFI.SHGFI_ICONLOCATION);
                var hasCustomIcon = ret != IntPtr.Zero && !shfi.szDisplayName.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.Windows));
                await args.Request.SendResponseAsync(new ValueSet()
                {
                    { "HasCustomIcon", hasCustomIcon }
                });

                break;

            default:
                if (args.Request.Message.ContainsKey("Application"))
                {
                    var application = (string)args.Request.Message["Application"];
                    HandleApplicationLaunch(application, args);
                }
                else if (args.Request.Message.ContainsKey("ApplicationList"))
                {
                    var applicationList = JsonConvert.DeserializeObject <IEnumerable <string> >((string)args.Request.Message["ApplicationList"]);
                    HandleApplicationsLaunch(applicationList, args);
                }
                break;
            }
        }
Esempio n. 23
0
        public static string GetTypeName(string strPath)
        {
            SHFILEINFO fileInfo = new SHFILEINFO();
            int cbFileInfo = Marshal.SizeOf(fileInfo);

            SHGetFileInfo(strPath, (uint)FileAttributeFlags.FILE_ATTRIBUTE_NORMAL,
                ref fileInfo, (uint)cbFileInfo, (uint)(GetFileInfoFlags.SHGFI_DISPLAYNAME | GetFileInfoFlags.SHGFI_TYPENAME));

            return fileInfo.szTypeName;
        }
Esempio n. 24
0
		/// <summary>
		/// Used to access system folder icons.
		/// </summary>
		/// <param name="size">Specify large or small icons.</param>
		/// <param name="folderType">Specify open or closed FolderType.</param>
		/// <returns>System.Drawing.Icon</returns>
		public static System.Drawing.Icon GetFolderIcon( IconSize size, FolderType folderType )
		{
			// Need to add size check, although errors generated at present!
			uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

			if (FolderType.Open == folderType)
			{
				flags |= Shell32.SHGFI_OPENICON;
			}
			
			if (IconSize.Small == size)
			{
				flags |= Shell32.SHGFI_SMALLICON;
			} 
			else 
			{
				flags |= Shell32.SHGFI_LARGEICON;
			}

			// Get the folder icon
			var shfi = new Shell32.SHFILEINFO();
			Shell32.SHGetFileInfo(	null, 
				Shell32.FILE_ATTRIBUTE_DIRECTORY, 
				ref shfi, 
				(uint) Marshal.SizeOf(shfi), 
				flags );

			System.Drawing.Icon.FromHandle(shfi.hIcon);	// Load the icon from an HICON handle

			// Now clone the icon, so that it can be successfully stored in an ImageList
			var icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

			User32.DestroyIcon( shfi.hIcon );		// Cleanup
			return icon;
		}	
Esempio n. 25
0
        public int AddRoot(string szSHA)
        {
            string szFolder = "FolderOpen";
            int nIndexOpen = 0, nIndexCloesed = 0;
            if (!_extensionList.ContainsKey(szFolder.ToUpper()))
            {
                nIndexOpen = base.ImageList.Images.Count;
                Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
                base.ImageList.Images.Add(IconReader.GetFolderIcon(IconReader.IconSize.Small, IconReader.FolderType.Open, ref shfi));
                _extensionList.Add(szFolder.ToUpper(), nIndexOpen);
            }
            else
            {
                 nIndexOpen = (int)_extensionList[szFolder.ToUpper()];
            }

            szFolder = "FolderClose";
            if (!_extensionList.ContainsKey(szFolder.ToUpper()))
            {
                nIndexCloesed = base.ImageList.Images.Count;
                Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
                base.ImageList.Images.Add(IconReader.GetFolderIcon(IconReader.IconSize.Small, IconReader.FolderType.Closed, ref shfi));
                _extensionList.Add(szFolder.ToUpper(), nIndexCloesed);
            }
            else
            {
                nIndexCloesed = (int)_extensionList[szFolder.ToUpper()];
            }

            TreeNode tmpNdoe = new TreeNode(szSHA);
            tmpNdoe.Tag = null;
            tmpNdoe.ImageIndex = nIndexOpen;
            tmpNdoe.SelectedImageIndex = nIndexOpen;
            return base.Nodes.Add(tmpNdoe);
        }
    public static Dictionary <string, Icon> GetPrintersWithIcons(IntPtr hwndOwner)
    {
        Dictionary <string, Icon> result = new Dictionary <string, Icon>();

        Shell32.IShellFolder iDesktopFolder = Shell32.GetDesktopFolder();
        try
        {
            IntPtr pidlPrintersFolder;
            if (Shell32.SHGetFolderLocation(hwndOwner, (int)Shell32.CSIDL.CSIDL_PRINTERS, IntPtr.Zero, 0, out pidlPrintersFolder) == 0)
            {
                try
                {
                    StringBuilder strDisplay       = new StringBuilder(260);
                    Guid          guidIShellFolder = Shell32.IID_IShellFolder;
                    IntPtr        ptrPrintersShellFolder;
                    iDesktopFolder.BindToObject(pidlPrintersFolder, IntPtr.Zero, ref guidIShellFolder, out ptrPrintersShellFolder);
                    Object objPrintersShellFolder = Marshal.GetTypedObjectForIUnknown(ptrPrintersShellFolder, Shell32.ShellFolderType);
                    try
                    {
                        Shell32.IShellFolder printersShellFolder = (Shell32.IShellFolder)objPrintersShellFolder;
                        IntPtr ptrObjectsList;
                        printersShellFolder.EnumObjects(hwndOwner, Shell32.ESHCONTF.SHCONTF_NONFOLDERS, out ptrObjectsList);
                        Object objEnumIDList = Marshal.GetTypedObjectForIUnknown(ptrObjectsList, Shell32.EnumIDListType);
                        try
                        {
                            Shell32.IEnumIDList iEnumIDList = (Shell32.IEnumIDList)objEnumIDList;
                            IntPtr[]            rgelt       = new IntPtr[1];
                            IntPtr         pidlPrinter;
                            int            pceltFetched;
                            Shell32.STRRET ptrString;
                            while (iEnumIDList.Next(1, rgelt, out pceltFetched) == 0 && pceltFetched == 1)
                            {
                                printersShellFolder.GetDisplayNameOf(rgelt[0],
                                                                     Shell32.ESHGDN.SHGDN_NORMAL, out ptrString);
                                if (Shell32.StrRetToBuf(ref ptrString, rgelt[0], strDisplay,
                                                        (uint)strDisplay.Capacity) == 0)
                                {
                                    pidlPrinter = Shell32.ILCombine(pidlPrintersFolder, rgelt[0]);
                                    string             printerDisplayNameInPrintersFolder = strDisplay.ToString();
                                    Shell32.SHFILEINFO shinfo = new Shell32.SHFILEINFO();
                                    Shell32.SHGetFileInfo(pidlPrinter, 0, out shinfo, (uint)Marshal.SizeOf(shinfo), Shell32.SHGFI.PIDL | Shell32.SHGFI.AddOverlays | Shell32.SHGFI.Icon);
                                    Icon printerIcon = (Icon)Icon.FromHandle(shinfo.hIcon).Clone();
                                    Shell32.DestroyIcon(shinfo.hIcon);
                                    result.Add(printerDisplayNameInPrintersFolder, printerIcon);
                                }
                            }
                        }
                        finally
                        {
                            Marshal.ReleaseComObject(objEnumIDList);
                        }
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(objPrintersShellFolder);
                    }
                }
                finally
                {
                    Shell32.ILFree(pidlPrintersFolder);
                }
            }
        }
        finally
        {
            Marshal.ReleaseComObject(iDesktopFolder);
        }
        return(result);
    }
Esempio n. 27
0
        /// <summary>
		/// Returns an icon for a given file - indicated by the name parameter.
		/// </summary>
		/// <param name="name">Pathname for file.</param>
		/// <returns>System.Drawing.Icon</returns>
		private Icon GetFileIcon(string name)
		{
            try{
			    Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
			    uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES | Shell32.SHGFI_SMALLICON;

			    Shell32.SHGetFileInfo(name, 
				    Shell32.FILE_ATTRIBUTE_NORMAL, 
				    ref shfi, 
				    (uint) System.Runtime.InteropServices.Marshal.SizeOf(shfi), 
				    flags );

			    // Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
			    System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
			    User32.DestroyIcon( shfi.hIcon );		// Cleanup
			    return icon;
            }
            catch{
                return ResManager.GetIcon("attach");
            }
		}
Esempio n. 28
0
        public int Add(TreeNode ParentNode, object TagContent,string szFileName,bool bIsParent)
        {
            //Check that we haven't already got the extension, if we have, then
            //return back its index
            if(bIsParent==false)
            {
                // Split it down so we can get the extension
                string[] splitPath = szFileName.Split(new Char[] { '.' });
                string szExtention = (string)splitPath.GetValue(splitPath.GetUpperBound(0));
                szExtention = "." + szExtention;

                if (_extensionList.ContainsKey(szExtention.ToUpper()))
                {
                    // it already exists
                    int nInex = (int)_extensionList[szExtention.ToUpper()]; //return existing index
                    //Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();

                    TreeNode tmpNdoe = new TreeNode(szFileName);
                    tmpNdoe.Tag = TagContent;
                    tmpNdoe.ImageIndex = nInex;
                    tmpNdoe.SelectedImageIndex = nInex;
                    return ParentNode.Nodes.Add(tmpNdoe);
                }
                else
                {
                    int pos = base.ImageList.Images.Count;
                    Shell32.SHFILEINFO shfi=new Shell32.SHFILEINFO();
                    base.ImageList.Images.Add(IconReader.GetFileIcon(szExtention,IconReader.IconSize.Small, false, ref shfi));
                    _extensionList.Add(szExtention.ToUpper(), pos);

                    TreeNode tmpNdoe = new TreeNode(szFileName);
                    tmpNdoe.Tag = TagContent;
                    tmpNdoe.ImageIndex = pos;
                    tmpNdoe.SelectedImageIndex = pos;
                    return ParentNode.Nodes.Add(tmpNdoe);
                }
            }
            else
            {
                string szFolder = "FolderClose";
                if (_extensionList.ContainsKey(szFolder.ToUpper()))
                {
                    // it already exists
                    int nInex = (int)_extensionList[szFolder.ToUpper()]; //return existing index
                    //Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();

                    TreeNode tmpNdoe = new TreeNode(szFileName);
                    tmpNdoe.Tag = TagContent;
                    tmpNdoe.ImageIndex = nInex;
                    tmpNdoe.SelectedImageIndex = nInex;
                    return ParentNode.Nodes.Add(tmpNdoe);
                }
                else
                {
                    int pos = base.ImageList.Images.Count;
                    Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
                    base.ImageList.Images.Add(IconReader.GetFolderIcon(IconReader.IconSize.Small, IconReader.FolderType.Closed, ref shfi));
                    _extensionList.Add(szFolder.ToUpper(), pos);

                    TreeNode tmpNdoe = new TreeNode(szFileName);
                    tmpNdoe.Tag = TagContent;
                    tmpNdoe.ImageIndex = pos;
                    tmpNdoe.SelectedImageIndex = pos;
                    return ParentNode.Nodes.Add(tmpNdoe);
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// 获取系统图标并缓存
        /// </summary>
        /// <param name="fsFullPath">完整路径</param>
        /// <param name="shFileInfo">同时传出文件系统信息</param>
        /// <param name="Expanded">是否获取展开图标</param>
        /// <returns></returns>
        public static Icon GetFileSystemIcon(string fsFullPath, ref Shell32.SHFILEINFO shFileInfo, bool Expanded = false)
        {
            if (!Path.IsPathRooted(fsFullPath))
            {
                return(null);
            }

            Icon SmallIcon = null;

            if (File.Exists(fsFullPath))
            {            //文件
                FileInfo diChild = new FileInfo(fsFullPath);
                string   strExt  = diChild.Extension.ToLower();
                if (strExt == ".exe")
                {
                    strExt = diChild.FullName.ToLower();
                }

                SmallIcon = Shell32.GetFileInfo(strExt, ref shFileInfo);

                if (!ImgList.Images.ContainsKey(strExt))
                {
                    ImgList.Images.Add(strExt, SmallIcon);
                }
            }
            else if (Directory.Exists(fsFullPath))
            {            //文件夹或盘符
                if (fsFullPath.Length == 3)
                {        //盘符
                    string    cDrive = fsFullPath.Substring(0, 1);
                    DriveInfo di     = new DriveInfo(cDrive);
                    SmallIcon = Shell32.GetFileInfo(fsFullPath, ref shFileInfo);

                    if (!ImgList.Images.ContainsKey(shFileInfo.szTypeName))
                    {
                        ImgList.Images.Add(shFileInfo.szTypeName, SmallIcon);
                    }
                }
                else if (Expanded)
                {                //文件夹展开
                    if (!ImgList.Images.ContainsKey("文件夹展开"))
                    {
                        SmallIcon = Shell32.GetFolderIcon(ref shFileInfo, false, true);
                        ImgList.Images.Add("文件夹展开", SmallIcon);
                    }
                    Bitmap bmp = new Bitmap(ImgList.Images["文件夹展开"]);
                    SmallIcon = Icon.FromHandle(bmp.GetHicon());
                }
                else
                {                //文件夹收起
                    if (!ImgList.Images.ContainsKey("文件夹收起"))
                    {
                        SmallIcon = Apq.DllImports.Shell32.GetFolderIcon(ref shFileInfo);
                        ImgList.Images.Add("文件夹收起", SmallIcon);
                    }
                    Bitmap bmp = new Bitmap(ImgList.Images["文件夹收起"]);
                    SmallIcon = Icon.FromHandle(bmp.GetHicon());
                }
            }
            else
            {            //盘符
                string    cDrive = fsFullPath.Substring(0, 1);
                DriveInfo di     = new DriveInfo(cDrive);
                SmallIcon = Shell32.GetFileInfo(fsFullPath, ref shFileInfo);

                if (!ImgList.Images.ContainsKey(shFileInfo.szTypeName))
                {
                    ImgList.Images.Add(shFileInfo.szTypeName, SmallIcon);
                }
            }

            return(SmallIcon);
        }
Esempio n. 30
0
 public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttribute, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint Flags);
        /// <summary>
        /// Used to access system folder icons.
        /// </summary>
        /// <param name="size">Specify large or small icons.</param>
        /// <param name="folderType">Specify open or closed FolderType.</param>
        /// <param name="shfi">Return Folder Information</param>
        /// <returns>System.Drawing.Icon</returns>
        public static Icon GetFolderIcon(IconSize size, FolderType folderType, ref Shell32.SHFILEINFO shfi)
        {
            // Need to add size check, although errors generated at present!
            Shell32.SHGetFileInfoConstants flags = Shell32.SHGetFileInfoConstants.SHGFI_TYPENAME | Shell32.SHGetFileInfoConstants.SHGFI_DISPLAYNAME | Shell32.SHGetFileInfoConstants.SHGFI_ICON | Shell32.SHGetFileInfoConstants.SHGFI_USEFILEATTRIBUTES;

            if (FolderType.Open == folderType)
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_OPENICON;

            if (IconSize.Small == size)
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_SMALLICON;
            else
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_LARGEICON;

            IntPtr hIml;
            // Get the folder icon
            shfi = new Shell32.SHFILEINFO();
            if (IconHelper.Utils.IsSevenOrAbove()) // Windows 7 FIX
            {
                hIml = Shell32.SHGetFileInfo(Environment.GetFolderPath(Environment.SpecialFolder.System),
                Shell32.FILE_ATTRIBUTE.DIRECTORY,
                ref shfi,
                (uint)Marshal.SizeOf(shfi),
                flags);
            }
            else
            {
                hIml = Shell32.SHGetFileInfo(null,
                Shell32.FILE_ATTRIBUTE.DIRECTORY,
                ref shfi,
                (uint)Marshal.SizeOf(shfi),
                flags);
            }
            if (shfi.hIcon == IntPtr.Zero) return null;
            if (!IconHelper.Utils.IsXpOrAbove()) return GetManagedIcon(shfi.hIcon);
            // Get the System IImageList object from the Shell:
            Guid iidImageList = new Guid("46EB5926-582E-4017-9FDF-E8998DAA0950");
            Shell32.IImageList iImageList = null;
            int ret = Shell32.SHGetImageList(
                (int)size,
                ref iidImageList,
                ref iImageList
                );

            // the image list handle is the IUnknown pointer, but
            // using Marshal.GetIUnknownForObject doesn't return
            // the right value.  It really doesn't hurt to make
            // a second call to get the handle:
            Shell32.SHGetImageListHandle((int)size, ref iidImageList, ref hIml);
            IntPtr hIcon = IntPtr.Zero;
            if (iImageList == null)
            {
                hIcon = Comctl32.ImageList_GetIcon(
                   hIml,
                   shfi.iIcon,
                   (int)Comctl32.ImageListDrawItemConstants.ILD_TRANSPARENT);
            }
            else
            {
                iImageList.GetIcon(
                   shfi.iIcon,
                   (int)Comctl32.ImageListDrawItemConstants.ILD_TRANSPARENT,
                   ref hIcon);
            }
            return hIcon == IntPtr.Zero ? GetManagedIcon(shfi.hIcon) : GetManagedIcon(hIcon);
        }
        /// <summary>
        /// Returns an icon for a given file - indicated by the name parameter.
        /// </summary>
        /// <param name="name">Extension or pathname for file.</param>
        /// <param name="size">Large or small</param>
        /// <param name="linkOverlay">Whether to include the link icon</param>
        /// <param name="shfi">Return File Information</param>
        /// <returns>System.Drawing.Icon</returns>
        public static Icon GetFileIcon(string name, IconSize size, bool linkOverlay, ref Shell32.SHFILEINFO shfi)
        {
            name = Environment.ExpandEnvironmentVariables(name);
            shfi = new Shell32.SHFILEINFO();
            Shell32.SHGetFileInfoConstants flags = Shell32.SHGetFileInfoConstants.SHGFI_TYPENAME | Shell32.SHGetFileInfoConstants.SHGFI_DISPLAYNAME | Shell32.SHGetFileInfoConstants.SHGFI_ICON | Shell32.SHGetFileInfoConstants.SHGFI_SHELLICONSIZE | Shell32.SHGetFileInfoConstants.SHGFI_SYSICONINDEX | Shell32.SHGetFileInfoConstants.SHGFI_USEFILEATTRIBUTES;

            if (linkOverlay) flags |= Shell32.SHGetFileInfoConstants.SHGFI_LINKOVERLAY;
            /* Check the size specified for return. */
            if (IconSize.Small == size)
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_SMALLICON;
            else
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_LARGEICON;

            IntPtr hIml = Shell32.SHGetFileInfo(name,
                Shell32.FILE_ATTRIBUTE.NORMAL,
                ref shfi,
                (uint)Marshal.SizeOf(shfi),
                flags);

            if (shfi.hIcon == IntPtr.Zero) return null;
            if (!IconHelper.Utils.IsXpOrAbove()) return GetManagedIcon(shfi.hIcon);
            // Get the System IImageList object from the Shell:
            Guid iidImageList = new Guid("46EB5926-582E-4017-9FDF-E8998DAA0950");
            Shell32.IImageList iImageList = null;
            int ret = Shell32.SHGetImageList(
                (int)size,
                ref iidImageList,
                ref iImageList
                );
            // the image list handle is the IUnknown pointer, but
            // using Marshal.GetIUnknownForObject doesn't return
            // the right value.  It really doesn't hurt to make
            // a second call to get the handle:
            Shell32.SHGetImageListHandle((int)size, ref iidImageList, ref hIml);

            IntPtr hIcon = IntPtr.Zero;
            if (iImageList == null)
            {
                hIcon = Comctl32.ImageList_GetIcon(
                    hIml,
                    shfi.iIcon,
                    (int)Comctl32.ImageListDrawItemConstants.ILD_TRANSPARENT);
            }
            else
            {
                iImageList.GetIcon(
                    shfi.iIcon,
                    (int)Comctl32.ImageListDrawItemConstants.ILD_TRANSPARENT,
                    ref hIcon);
            }
            return hIcon == IntPtr.Zero ? GetManagedIcon(shfi.hIcon) : GetManagedIcon(hIcon);
        }
Esempio n. 33
0
        private Icon GetFileIconFromExtension(string filename, bool isFolder, IconSize size, bool linkOverlay)
        {
            //by extension
            string key = Utils.GetSafeExtension(filename);

            if (isFolder)
            {
                key += "-folder";
            }
            if (linkOverlay)
            {
                key += "-overlay";
            }
            int  s    = size == IconSize.Small ? 16 : 32;
            Icon icon = _iconCache.Get(key, s);

            if (null == icon)
            {
                Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
                uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

                if (linkOverlay)
                {
                    flags += Shell32.SHGFI_LINKOVERLAY;
                }

                /* Check the size specified for return. */
                if (IconSize.Small == size)
                {
                    flags += Shell32.SHGFI_SMALLICON;
                }
                else
                {
                    flags += Shell32.SHGFI_LARGEICON;
                }

                uint fileAttributes = 0;
                if (isFolder)
                {
                    fileAttributes = Shell32.FILE_ATTRIBUTE_DIRECTORY;
                }
                else
                {
                    fileAttributes = Shell32.FILE_ATTRIBUTE_NORMAL;
                }

                IntPtr hSuccess = Shell32.SHGetFileInfo(filename, fileAttributes, ref shfi, (uint)Marshal.SizeOf(shfi),
                                                        flags);
                if (hSuccess != IntPtr.Zero)
                {
                    // Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
                    try
                    {
                        icon = (Icon)Icon.FromHandle(shfi.hIcon).Clone();
                    }
                    catch (Exception)
                    {
                        Log.error("Cannot get icon for " + filename);
                        return(Icon.FromHandle(IconForName("notfound", size).GetHicon()));
                    }
                    _iconCache.Put(key, icon, s);
                    // Release icon handle
                    User32.DestroyIcon(shfi.hIcon);
                }
            }
            return(icon);
        }
Esempio n. 34
0
        public static (string icon, string overlay, bool isCustom) GetFileIconAndOverlay(string path, int thumbnailSize)
        {
            var shfi = new Shell32.SHFILEINFO();
            var ret  = Shell32.SHGetFileInfo(
                path,
                0,
                ref shfi,
                Shell32.SHFILEINFO.Size,
                Shell32.SHGFI.SHGFI_OVERLAYINDEX | Shell32.SHGFI.SHGFI_ICON | Shell32.SHGFI.SHGFI_SYSICONINDEX | Shell32.SHGFI.SHGFI_ICONLOCATION);

            if (ret == IntPtr.Zero)
            {
                return(null, null, false);
            }

            bool isCustom = !shfi.szDisplayName.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.Windows));

            User32.DestroyIcon(shfi.hIcon);
            Shell32.SHGetImageList(Shell32.SHIL.SHIL_LARGE, typeof(ComCtl32.IImageList).GUID, out var tmp);
            using var imageList = ComCtl32.SafeHIMAGELIST.FromIImageList(tmp);
            if (imageList.IsNull || imageList.IsInvalid)
            {
                return(null, null, isCustom);
            }

            string iconStr = null, overlayStr = null;
            var    overlayIdx = shfi.iIcon >> 24;

            if (overlayIdx != 0)
            {
                var overlayImage = imageList.Interface.GetOverlayImage(overlayIdx);
                using var hOverlay = imageList.Interface.GetIcon(overlayImage, ComCtl32.IMAGELISTDRAWFLAGS.ILD_TRANSPARENT);
                if (!hOverlay.IsNull && !hOverlay.IsInvalid)
                {
                    using var image = hOverlay.ToIcon().ToBitmap();
                    byte[] bitmapData = (byte[])new ImageConverter().ConvertTo(image, typeof(byte[]));
                    overlayStr = Convert.ToBase64String(bitmapData, 0, bitmapData.Length);
                }
            }

            // The following only returns the icon (not thumbnail) and it's difficult to get a high-res icon
            //var icon_idx = shfi.iIcon & 0xFFFFFF;
            //using var hIcon = imageList.Interface.GetIcon(icon_idx, ComCtl32.IMAGELISTDRAWFLAGS.ILD_TRANSPARENT);

            using var shellItem = new Vanara.Windows.Shell.ShellItem(path);
            if (shellItem.IShellItem is Shell32.IShellItemImageFactory fctry)
            {
                var flags = Shell32.SIIGBF.SIIGBF_BIGGERSIZEOK;
                if (thumbnailSize < 80)
                {
                    flags |= Shell32.SIIGBF.SIIGBF_ICONONLY;
                }
                var hres = fctry.GetImage(new SIZE(thumbnailSize, thumbnailSize), flags, out var hbitmap);
                if (hres == HRESULT.S_OK)
                {
                    using var image = GetBitmapFromHBitmap(hbitmap);
                    if (image != null)
                    {
                        byte[] bitmapData = (byte[])new ImageConverter().ConvertTo(image, typeof(byte[]));
                        iconStr = Convert.ToBase64String(bitmapData, 0, bitmapData.Length);
                    }
                }
                //Marshal.ReleaseComObject(fctry);
            }

            return(iconStr, overlayStr, isCustom);
        }
Esempio n. 35
0
        /// <summary>
        /// Get Shell file or folder info with extra flags.
        /// </summary>
        private static ShellObject GetInfo(Shell32.FileInfoItemType identifier, string name, Shell32.FileInfoFlag extraFlags)
        {
            // Create a filesystemobject to hold the result
            ShellObject result = new ShellObject();

            // Create a structure to hold the information
            Shell32.SHFILEINFO info = new Shell32.SHFILEINFO();
            int infoSize = Marshal.SizeOf(typeof(Shell32.SHFILEINFO));

            // Build the flags
            Shell32.FileInfoFlag flags = Shell32.FileInfoFlag.Icon | Shell32.FileInfoFlag.UseFileAttributes;
            flags |= extraFlags;

            // Retrieve the small icon
            Shell32.SHGetFileInfo(name, identifier, ref info, infoSize, flags | Shell32.FileInfoFlag.IconSizeSmall);
            result.SmallIcon = Icon.FromHandle(info.hIcon).ToBitmap();
            User32.DestroyIcon(info.hIcon);

            // Retrieve the large icon and type info
            Shell32.SHGetFileInfo(name, identifier, ref info, infoSize, flags | Shell32.FileInfoFlag.IconSizeLarge | Shell32.FileInfoFlag.TypeName);
            result.LargeIcon = Icon.FromHandle(info.hIcon).ToBitmap();
            result.TypeName = info.szTypeName;
            User32.DestroyIcon(info.hIcon);

            return result;
        }