none
wpf获取文件图标图片显示时有点模糊和如何获得文件夹图标?,如何解决? RRS feed

  • 问题


  • 如上图所示,获取文件图标,采用listview显示文件图标和文件名,发现有点模糊,怎么解决?

    文件图标获取方法如下显示

    private ImageSource GetIcon(string FilePath)

            {
                System.Windows.Media.ImageSource icon=null;
                if (icon == null && System.IO.File.Exists(FilePath))
                {
                    using (System.Drawing.Icon sysicon = System.Drawing.Icon.ExtractAssociatedIcon(FilePath))
                    {
                        icon = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                                  sysicon.Handle,
                                  System.Windows.Int32Rect.Empty,
                                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                    }
                }

                return icon;

            }


    请求解决办法!

    2016年8月25日 13:07

答案

  • 您好 轮回的齿轮,

    >>“如上图所示,获取文件图标,采用listview显示文件图标和文件名,发现有点模糊,怎么解决?”

    由于系统 图标本身大小的限制,你如果放大显示图片尺寸,就会变得模糊。 但是你可以通过下面的方法获取尺寸为16X16和32X32的图标。不建议你放大使用。 下面的简单例子供你参考。

    文件夹图标:
    获取文件夹图标,下面的方法中直接调取ShellIcon.GetLargeFolderIcon() 即可。 因为文件夹图标是一致的。

    XAML:

    <Window x:Class="Wpf_Example_LY.lineChart"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:Wpf_Example_LY"
            mc:Ignorable="d"
            Title="lineChart" Height="300" Width="300">
        <Window.Resources>
            <ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
                <WrapPanel IsItemsHost="True"/>
            </ItemsPanelTemplate>
            <Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="Padding" Value="2,0,0,0"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}">
                            <Border HorizontalAlignment="Center" VerticalAlignment="Center">
                                <StackPanel Orientation="Vertical">
                                    <Image x:Name="img" Source="{Binding FileIcon}" Height="64" Width="64"/>
                                    <TextBlock VerticalAlignment="Center" Width="75" TextWrapping="Wrap" Text="{Binding FileName}"/>
                                </StackPanel>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Window.Resources>
        <Grid>
            <Button x:Name="btnBrowse" Click="btnBrowse_Click"
                    Content="Browse" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" VerticalAlignment="Top" Width="119"/>
            <ListView x:Name="lbFiles" 
                     ItemContainerStyle="{DynamicResource ListBoxItemStyle}"
                     ItemsPanel="{DynamicResource ItemsPanelTemplate1}"
                     Margin="12,51,12,12" ScrollViewer.VerticalScrollBarVisibility="Visible" />
            
            <!--<ListView   x:Name="lbFiles2"  ></ListView>-->
        </Grid>
    </Window>

    C# code:

    ObservableCollection<MyFiles> myFilesList = new ObservableCollection<MyFiles>();
    public lineChart()
    {
        InitializeComponent();
    }
    
    #region Button-Click-btnBrowse
    private void btnBrowse_Click(object sender, RoutedEventArgs e)
    {
        System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
        ofd.Filter = "All files (*.*)|*.*";
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string filePath = ofd.FileName;
            ImageSource imgSource = ShellIcon.ToImageSource(ShellIcon.GetLargeIcon(filePath));
            ImageSource imgSourcefolder = ShellIcon.ToImageSource(ShellIcon.GetLargeFolderIcon());
            myFilesList.Add(new MyFiles { FileName = ofd.SafeFileName, FileIcon = imgSource });
            myFilesList.Add(new MyFiles { FileName = "your folderpath", FileIcon = imgSourcefolder });
        }
        lbFiles.ItemsSource = myFilesList;
    }
    #endregion
    
    public class MyFiles
    {
        public string FileName
        {
            get;
            set;
        }
        public ImageSource FileIcon { get; set; }
    }
    
    ShellIcon:
    
    public static class ShellIcon
    {
        #region Interop constants
    
        private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
        private const uint FILE_ATTRIBUTE_DIRECTORY = 0x10;
    
        #endregion
    
        #region Interop data types
    
        [StructLayout(LayoutKind.Sequential)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }
    
        [Flags]
        private enum SHGFI : int
        {
            /// <summary>get icon</summary>
            Icon = 0x000000100,
            /// <summary>get display name</summary>
            DisplayName = 0x000000200,
            /// <summary>get type name</summary>
            TypeName = 0x000000400,
            /// <summary>get attributes</summary>
            Attributes = 0x000000800,
            /// <summary>get icon location</summary>
            IconLocation = 0x000001000,
            /// <summary>return exe type</summary>
            ExeType = 0x000002000,
            /// <summary>get system icon index</summary>
            SysIconIndex = 0x000004000,
            /// <summary>put a link overlay on icon</summary>
            LinkOverlay = 0x000008000,
            /// <summary>show icon in selected state</summary>
            Selected = 0x000010000,
            /// <summary>get only specified attributes</summary>
            Attr_Specified = 0x000020000,
            /// <summary>get large icon</summary>
            LargeIcon = 0x000000000,
            /// <summary>get small icon</summary>
            SmallIcon = 0x000000001,
            /// <summary>get open icon</summary>
            OpenIcon = 0x000000002,
            /// <summary>get shell size icon</summary>
            ShellIconSize = 0x000000004,
            /// <summary>pszPath is a pidl</summary>
            PIDL = 0x000000008,
            /// <summary>use passed dwFileAttribute</summary>
            UseFileAttributes = 0x000000010,
            /// <summary>apply the appropriate overlays</summary>
            AddOverlays = 0x000000020,
            /// <summary>Get the index of the overlay in the upper 8 bits of the iIcon</summary>
            OverlayIndex = 0x000000040,
        }
    
        #endregion
    
        private class Win32
        {
            [DllImport("shell32.dll")]
            public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
    
            [DllImport("User32.dll")]
            public static extern int DestroyIcon(IntPtr hIcon);
    
        }
    
        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);
    
    
        public static Icon GetSmallFolderIcon()
        {
            return GetIcon("folder", SHGFI.SmallIcon | SHGFI.UseFileAttributes, true);
        }
    
        public static Icon GetLargeFolderIcon()
        {
            return GetIcon("folder", SHGFI.LargeIcon | SHGFI.UseFileAttributes, true);
        }
    
        public static Icon GetSmallIcon(string fileName)
        {
            return GetIcon(fileName, SHGFI.SmallIcon);
        }
    
        public static Icon GetLargeIcon(string fileName)
        {
            return GetIcon(fileName, SHGFI.LargeIcon);
        }
    
        public static Icon GetSmallIconFromExtension(string extension)
        {
            return GetIcon(extension, SHGFI.SmallIcon | SHGFI.UseFileAttributes);
        }
    
        public static Icon GetLargeIconFromExtension(string extension)
        {
            return GetIcon(extension, SHGFI.LargeIcon | SHGFI.UseFileAttributes);
        }
    
        private static Icon GetIcon(string fileName, SHGFI flags, bool isFolder = false)
        {
            SHFILEINFO shinfo = new SHFILEINFO();
    
            IntPtr hImgSmall = Win32.SHGetFileInfo(fileName, isFolder ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL, ref shinfo, (uint)Marshal.SizeOf(shinfo), (uint)(SHGFI.Icon | flags));
    
            Icon icon = (Icon)System.Drawing.Icon.FromHandle(shinfo.hIcon).Clone();
            Win32.DestroyIcon(shinfo.hIcon);
            return icon;
        }
    
        public static ImageSource ToImageSource(this Icon icon)
        {
            Bitmap bitmap = icon.ToBitmap();
            IntPtr hBitmap = bitmap.GetHbitmap();
    
            ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
    
            if (!DeleteObject(hBitmap))
            {
                throw new Win32Exception();
            }
            return wpfBitmap;
        }
    }
    Best Regards,
    Li Wang

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2016年8月28日 2:15