Пример #1
0
        /// <summary>
        /// Gets the icon as an <see cref="ImageSource"/> for the specified path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="info">The shell file info.</param>
        /// <returns>The icon as an <see cref="ImageSource"/> for the specified path.</returns>
        public static ImageSource GetImageSource(string path, out Win32.SHFILEINFO info)
        {
            info = new Win32.SHFILEINFO();

            int attr;
            if (Directory.Exists(path))
                attr = (int)Win32.FILE_ATTRIBUTE_DIRECTORY;
            else if (File.Exists(path))
                attr = (int)Win32.FILE_ATTRIBUTE_NORMAL;
            else if (path.Length == 3) // drive not ready
                attr = (int)Win32.FILE_ATTRIBUTE_DIRECTORY;
            else
                return null;

            Win32.SHGetFileInfo(path, attr, out info, (uint)Marshal.SizeOf(typeof(Win32.SHFILEINFO)), Win32.SHGFI_DISPLAYNAME | Win32.SHGFI_ICON | Win32.SHGFI_TYPENAME | Win32.SHGFI_SMALLICON | Win32.SHGFI_USEFILEATTRIBUTES);

            ImageSource img = null;
            if (info.hIcon != IntPtr.Zero)
            {
                using (Icon icon = Icon.FromHandle(info.hIcon))
                {
                    img = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, new Int32Rect(0, 0, icon.Width, icon.Height), BitmapSizeOptions.FromEmptyOptions());
                }

                Win32.DestroyIcon(info.hIcon);
            }

            return img;
        }
Пример #2
0
        // ファイルに関連付くアイコンの取得
        private Icon GetFileIcon(string path)
        {
            var    shinfo   = new Win32.SHFILEINFO();
            IntPtr hSuccess = Win32.SHGetFileInfo(path, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON);

            if (hSuccess != IntPtr.Zero)
            {
                return(Icon.FromHandle(shinfo.hIcon));
            }
            return(null);
        }
Пример #3
0
        private void Form1_Load(object sender, EventArgs e)
        {
            var shinfo = new Win32.SHFILEINFO();

            Win32.SHGetFileInfo("0000000000.DOCX", 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON | Win32.SHGFI_USEFILEATTRIBUTES);
            var icon = (Icon)Icon.FromHandle(shinfo.hIcon).Clone();

            Win32.DestroyIcon(shinfo.hIcon);
            this.BackgroundImage = icon.ToBitmap();
            icon.Dispose();
        }
Пример #4
0
 /// <summary>
 /// Get the associated Icon for a file or application, this method always returns
 /// an icon. If the strPath is invalid or there is no icon, the default icon is returned.
 /// </summary>
 public static Icon GetFolderIcon(String path, Boolean small, Boolean overlays)
 {
     Win32.SHFILEINFO info = new Win32.SHFILEINFO(true);
     Int32 cbFileInfo = Marshal.SizeOf(info);
     Win32.SHGFI flags = Win32.SHGFI.Icon | Win32.SHGFI.UseFileAttributes;
     if (small) flags |= Win32.SHGFI.SmallIcon; else flags |= Win32.SHGFI.LargeIcon;
     if (overlays) flags |= Win32.SHGFI.AddOverlays; // Get overlays too...
     Win32.SHGetFileInfo(path, 0x00000010, out info, (UInt32)cbFileInfo, flags);
     Icon icon = (Icon)Icon.FromHandle(info.hIcon).Clone();
     Win32.DestroyIcon(info.hIcon);
     return icon;
 }
Пример #5
0
        /// <summary>
        /// Returns the shell display name of the specified path.
        /// If the path is nonexistent or it is failed, the file name returned by the Path.GetFileName method is returned.
        /// </summary>
        /// <param name="path">The path to evaluate. Null is not allowed.</param>
        /// <returns>The shell display name if it succeeds; otherwise, the file name returned by the Path.GetFileName method.</returns>
        public static string GetDisplayName(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            // Calls the SHGetFileInfo function.
            Win32.SHFILEINFO shFileInfo = new Win32.SHFILEINFO();
            if (Win32.SHGetFileInfo(path, 0, ref shFileInfo, (uint)Win32.SizeOfSHFILEINFO, Win32.SHGFI_DISPLAYNAME) == IntPtr.Zero)
            {
                return(Path.GetFileName(path));
            }

            // Returns the shell display name.
            return(shFileInfo.szDisplayName);
        }
Пример #6
0
        /// <summary>
        /// Get the associated Icon for a file or application, this method always returns
        /// an icon. If the strPath is invalid or there is no icon, the default icon is returned.
        /// </summary>
        public static Icon GetFolderIcon(String path, Boolean small, Boolean overlays)
        {
            Win32.SHFILEINFO info       = new Win32.SHFILEINFO(true);
            Int32            cbFileInfo = Marshal.SizeOf(info);

            Win32.SHGFI flags = Win32.SHGFI.Icon | Win32.SHGFI.UseFileAttributes;
            if (small)
            {
                flags |= Win32.SHGFI.SmallIcon;
            }
            else
            {
                flags |= Win32.SHGFI.LargeIcon;
            }
            if (overlays)
            {
                flags |= Win32.SHGFI.AddOverlays;           // Get overlays too...
            }
            Win32.SHGetFileInfo(path, 0x00000010, out info, (UInt32)cbFileInfo, flags);
            Icon icon = (Icon)Icon.FromHandle(info.hIcon).Clone();

            Win32.DestroyIcon(info.hIcon);
            return(icon);
        }
Пример #7
0
        //获取指定路径下所有文件及其图标
        public void GetListViewItem(string path, ImageList imglist, ListView lv)
        {
            lv.Items.Clear();
            Win32.SHFILEINFO shfi = new Win32.SHFILEINFO();
            try
            {
                string[] dirs = Directory.GetDirectories(path);
                string[] files = Directory.GetFiles(path);
                for (int i = 0; i < dirs.Length; i++)
                {
                    string[] info = new string[4];
                    DirectoryInfo dir = new DirectoryInfo(dirs[i]);
                    if (dir.Name == "RECYCLER" || dir.Name == "RECYCLED" || dir.Name == "Recycled" || dir.Name == "System Volume Information")
                    { }
                    else
                    {
                        //获得图标
                        Win32.SHGetFileInfo(dirs[i],
                                            (uint)0x80,
                                            ref shfi,
                                            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                            (uint)(0x100 | 0x400)); //取得Icon和TypeName
                        //添加图标
                        imglist.Images.Add(dir.Name, (Icon)Icon.FromHandle(shfi.hIcon).Clone());
                        info[0] = dir.Name.Remove(dir.Name.LastIndexOf("."));
                        info[1] = "";
                        info[2] = "文件夹";
                        info[3] = dir.LastWriteTime.ToString();
                        ListViewItem item = new ListViewItem(info, dir.Name);
                        lv.Items.Add(item);
                        //销毁图标
                        Win32.DestroyIcon(shfi.hIcon);
                    }
                }
                for (int i = 0; i < files.Length; i++)
                {
                    string[] info = new string[4];
                    FileInfo fi = new FileInfo(files[i]);
                    string Filetype = fi.Name.Substring(fi.Name.LastIndexOf(".") + 1, fi.Name.Length - fi.Name.LastIndexOf(".") - 1);
                    string newtype = Filetype.ToLower();
                    if (newtype == "sys" || newtype == "ini" || newtype == "bin" || newtype == "log" || newtype == "com" || newtype == "bat" || newtype == "db")
                    { }
                    else
                    {

                        //获得图标
                        Win32.SHGetFileInfo(files[i],
                                            (uint)0x80,
                                            ref shfi,
                                            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                            (uint)(0x100 | 0x400)); //取得Icon和TypeName
                        //添加图标
                        imglist.Images.Add(fi.Name, (Icon)Icon.FromHandle(shfi.hIcon).Clone());
                        info[0] = fi.Name.Remove(fi.Name.LastIndexOf("."));
                        info[1] = fi.Length.ToString();
                        info[2] = fi.Extension.ToString();
                        info[3] = fi.LastWriteTime.ToString();
                        ListViewItem item = new ListViewItem(info, fi.Name);
                        lv.Items.Add(item);
                        //销毁图标
                        Win32.DestroyIcon(shfi.hIcon);
                    }
                }
            }
            catch
            {
                MessageBox.Show("发生未知错误", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Пример #8
0
 public void GetListViewItem(string path, ImageList imglist, ListView lv)//获取指定路径下所有文件及其图标
 {
     lv.Items.Clear();
     Win32.SHFILEINFO shfi = new Win32.SHFILEINFO();
     try
     {
         string[] dirs  = Directory.GetDirectories(path);
         string[] files = Directory.GetFiles(path);
         for (int i = 0; i < dirs.Length; i++)
         {
             string[]      info = new string[4];
             DirectoryInfo dir  = new DirectoryInfo(dirs[i]);
             if (dir.Name == "RECYCLER" || dir.Name == "RECYCLED" || dir.Name == "Recycled" || dir.Name == "System Volume Information")
             {
             }
             else
             {
                 //获得图标
                 Win32.SHGetFileInfo(dirs[i],
                                     (uint)0x80,
                                     ref shfi,
                                     (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                     (uint)(0x100 | 0x400)); //取得Icon和TypeName
                 //添加图标
                 imglist.Images.Add(dir.Name, (Icon)Icon.FromHandle(shfi.hIcon).Clone());
                 info[0] = dir.Name.Remove(dir.Name.LastIndexOf("."));
                 info[1] = "";
                 info[2] = "文件夹";
                 info[3] = dir.LastWriteTime.ToString();
                 ListViewItem item = new ListViewItem(info, dir.Name);
                 lv.Items.Add(item);
                 //销毁图标
                 Win32.DestroyIcon(shfi.hIcon);
             }
         }
         for (int i = 0; i < files.Length; i++)
         {
             string[] info     = new string[4];
             FileInfo fi       = new FileInfo(files[i]);
             string   Filetype = fi.Name.Substring(fi.Name.LastIndexOf(".") + 1, fi.Name.Length - fi.Name.LastIndexOf(".") - 1);
             string   newtype  = Filetype.ToLower();
             if (newtype == "sys" || newtype == "ini" || newtype == "bin" || newtype == "log" || newtype == "com" || newtype == "bat" || newtype == "db")
             {
             }
             else
             {
                 //获得图标
                 Win32.SHGetFileInfo(files[i],
                                     (uint)0x80,
                                     ref shfi,
                                     (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
                                     (uint)(0x100 | 0x400)); //取得Icon和TypeName
                 //添加图标
                 imglist.Images.Add(fi.Name, (Icon)Icon.FromHandle(shfi.hIcon).Clone());
                 info[0] = fi.Name.Remove(fi.Name.LastIndexOf("."));
                 info[1] = fi.Length.ToString();
                 info[2] = fi.Extension.ToString();
                 info[3] = fi.LastWriteTime.ToString();
                 ListViewItem item = new ListViewItem(info, fi.Name);
                 lv.Items.Add(item);
                 //销毁图标
                 Win32.DestroyIcon(shfi.hIcon);
             }
         }
     }
     catch
     {
         MessageBox.Show("发生未知错误", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
     }
 }
Пример #9
0
        private void LoadFiles()
        {
            lstFiles.BeginUpdate();
            lstFiles.Items.Clear();

            if (treDirectories.SelectedNode.Tag is IEnumerable <ArchiveFileInfo> files)
            {
                foreach (var file in files)
                {
                    // Get the items from the file system, and add each of them to the ListView,
                    // complete with their corresponding name and icon indices.
                    var ext          = Path.GetExtension(file.FileName).ToLower();
                    var kuriimuFile  = ext.Length > 0 && _textExtensions.Contains(ext);
                    var kukkiiFile   = ext.Length > 0 && _imageExtensions.Contains(ext);
                    var karameruFile = ext.Length > 0 && _archiveExtensions.Contains(ext);

                    var shfi = new Win32.SHFILEINFO();
                    try
                    {
                        if (!imlFiles.Images.ContainsKey(ext) && !string.IsNullOrEmpty(ext))
                        {
                            Win32.SHGetFileInfo(ext, 0, out shfi, Marshal.SizeOf(shfi), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON | Win32.SHGFI_USEFILEATTRIBUTES);
                            imlFiles.Images.Add(ext, Icon.FromHandle(shfi.hIcon));
                        }
                    }
                    finally
                    {
                        if (shfi.hIcon != IntPtr.Zero)
                        {
                            Win32.DestroyIcon(shfi.hIcon);
                        }
                    }
                    try
                    {
                        if (!imlFilesLarge.Images.ContainsKey(ext) && !string.IsNullOrEmpty(ext))
                        {
                            Win32.SHGetFileInfo(ext, 0, out shfi, Marshal.SizeOf(shfi), Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON | Win32.SHGFI_USEFILEATTRIBUTES);
                            imlFilesLarge.Images.Add(ext, Icon.FromHandle(shfi.hIcon));
                        }
                    }
                    finally
                    {
                        if (shfi.hIcon != IntPtr.Zero)
                        {
                            Win32.DestroyIcon(shfi.hIcon);
                        }
                    }

                    if (kuriimuFile)
                    {
                        ext = "tree-text-file";
                    }
                    if (kukkiiFile)
                    {
                        ext = "tree-image-file";
                    }
                    if (karameruFile)
                    {
                        ext = "tree-archive-file";
                    }

                    var sb = new StringBuilder(16);
                    Win32.StrFormatByteSize((long)file.FileSize, sb, 16);
                    lstFiles.Items.Add(new ListViewItem(new[] { Path.GetFileName(file.FileName), sb.ToString() }, ext, StateToColor(file.State), Color.Transparent, lstFiles.Font)
                    {
                        Tag = file
                    });
                }

                tslFileCount.Text = $"Files: {files.Count()}";
            }

            lstFiles.EndUpdate();
        }
Пример #10
0
        /// <summary>
        /// Returns a fronzen ImageSource that is the shell icon of the specified path.
        /// </summary>
        /// <param name="path">The file/folder relative/abolute path. Nonexistent path is allowed. Null is not allowed.</param>
        /// <param name="shellIconSize">The icon size.</param>
        /// <param name="includeOverlay">Whether the overlay is displayed or not. It is ignored except these icon sizes: ShellIconSize.ShellSized, ShellIconSize.Small, ShellIconSize.Large.</param>
        /// <param name="includeLinkOverlay">Whether the link overlay is displayed or not. It is ignored except these icon sizes: ShellIconSize.ShellSized, ShellIconSize.Small, ShellIconSize.Large.</param>
        /// <param name="isOpen">Whether the open icon is returned or not.</param>
        /// <param name="isSelected">Whether the selected icon is returned or not.</param>
        /// <returns>A frozen ImageSource that is the shell icon.</returns>
        public static ImageSource GetIcon(string path, ShellIconSize shellIconSize, bool includeOverlay = false, bool includeLinkOverlay = false, bool isOpen = false, bool isSelected = false)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            // Creates a uFlags for the SHGetFileInfo function.
            uint uFlags = Win32.SHGFI_ICON | Win32.SHGFI_USEFILEATTRIBUTES;

            if (includeOverlay)
            {
                uFlags |= Win32.SHGFI_ADDOVERLAYS;
            }

            if (includeLinkOverlay)
            {
                uFlags |= Win32.SHGFI_LINKOVERLAY;
            }

            if (isOpen)
            {
                uFlags |= Win32.SHGFI_OPENICON;
            }

            if (isSelected)
            {
                uFlags |= Win32.SHGFI_SELECTED;
            }


            // Whether the shFileInfo structure's hIcon handle can be used to make the requested sized icon.
            bool isShFileInfoEnough = false;

            if (shellIconSize == ShellIconSize.ShellSized)
            {
                uFlags            |= Win32.SHGFI_SHELLICONSIZE;
                isShFileInfoEnough = true;
            }
            else if (shellIconSize == ShellIconSize.Small)
            {
                uFlags            |= Win32.SHGFI_SMALLICON;
                isShFileInfoEnough = true;
            }
            else if (shellIconSize == ShellIconSize.Large)
            {
                uFlags            |= Win32.SHGFI_LARGEICON;
                isShFileInfoEnough = true;
            }


            // Creates a dwFileAttributes for the SHGetFileInfo function.
            uint dwFileAttributes = Win32.FILE_ATTRIBUTE_NORMAL;

            if (Directory.Exists(path))
            {
                dwFileAttributes |= Win32.FILE_ATTRIBUTE_DIRECTORY;
            }


            // Calls the SHGetFileInfo function.
            Win32.SHFILEINFO shFileInfo = new Win32.SHFILEINFO();
            if (Win32.SHGetFileInfo(path, dwFileAttributes, ref shFileInfo, (uint)Win32.SizeOfSHFILEINFO, uFlags) == IntPtr.Zero)
            {
                throw new Exception("SHGetFileInfo function has failed.");
            }


            try
            {
                // If shFileInfo's hIcon is enough
                if (isShFileInfoEnough)
                {
                    return(ToImageSource(shFileInfo.hIcon));
                }
            }
            finally
            {
                // Releases the icon handle.
                if (shFileInfo.hIcon != IntPtr.Zero)
                {
                    if (Win32.DestroyIcon(shFileInfo.hIcon) == 0)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    shFileInfo.hIcon = IntPtr.Zero;
                }
            }


            // A iImageList for the SHGetImageList function.
            int iImageList;

            switch (shellIconSize)
            {
            case ShellIconSize.SystemSmall:
                iImageList = Win32.SHIL_SYSSMALL;
                break;

            case ShellIconSize.ExtraLarge:
                iImageList = Win32.SHIL_EXTRALARGE;
                break;

            case ShellIconSize.Jumbo:
                iImageList = Win32.SHIL_JUMBO;
                break;

            default:
                throw new InvalidOperationException(string.Format("The ShellIconSize.{0} is unknown.", shellIconSize));
            }


            // Gets a image list.
            Guid   IID_IImageList = Win32.IID_IImageList;
            IntPtr hImageList     = IntPtr.Zero;

            Marshal.ThrowExceptionForHR(Win32.SHGetImageList(iImageList, ref IID_IImageList, ref hImageList));


            // Gets an icon handle from the image list.
            IntPtr hIcon = Win32.ImageList_GetIcon(hImageList, shFileInfo.iIcon, Win32.ILD_TRANSPARENT);

            if (hIcon == IntPtr.Zero)
            {
                throw new Exception("ImageList_GetIcon function has failed.");
            }


            // TODO: Show overlay on the image list icon.


            try
            {
                // Returns the ImageSource.
                return(ToImageSource(hIcon));
            }
            finally
            {
                // Releases the icon handle.
                if (Win32.DestroyIcon(hIcon) == 0)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
        }