简体   繁体   中英

Getting icon from exe in .net compact framework

I am developing some windows forms application for Windows Embedded Compact 7 that imitates desktop shell using .net compact framework and c# Smart Device project type. I use SHGetFileInfo WinAPI function to get associated icon from exe file, here is my code below:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHFILEINFO
{
    public IntPtr hIcon;
    public IntPtr iIcon;
    public uint dwAttributes; 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    public string szDisplayName;      
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string szTypeName; 

    public SHFILEINFO(bool setDefaults)
    {
        hIcon = IntPtr.Zero;
        iIcon = IntPtr.Zero;
        dwAttributes = 0;
        szDisplayName = "";
        szTypeName = "";
    }
}
public class Win32
{
    public const uint SHGFI_ICON = 0x000000100; 
    public const uint SHGFI_LARGEICON = 0x00000000; 
    public const uint SHGFI_SMALLICON = 0x00000001; 

    [DllImport("coredll.dll")]
    public static extern IntPtr SHGetFileInfo(string pszPath,
                                              int dwFileAttributes,
                                              ref SHFILEINFO psfi,
                                              uint cbSizeFileInfo,
                                              uint uFlags);
 }

and then I call this function from here:

private static Icon ExtractIconFromExe(string targetPath)
{
IntPtr hImgLarge; 
var shinfo = new SHFILEINFO();
hImgLarge = Win32.SHGetFileInfo(targetPath,
                                0,
                                ref shinfo,
                                (uint)Marshal.SizeOf(shinfo),
                                Win32.SHGFI_ICON);
var icon = Icon.FromHandle(shinfo.hIcon);
return icon;
}

It's works fine on my Windows 7 Ultimate (using shell32.dll instead coredll.dll of course), but when I try to run this code on Windows Embedded or Smart Device emulator I have uninformative exception in this line: Icon.FromHandle(shinfo.hIcon) . Does anybody know how to solve my problem?

What file is targetPath ? Does it exist on Windows Embedded? Is it Empty or Null? We don't know!

Put some error checking code in there.

Your IntPtr hImgLarg is set specifically so you can verify the return value is not an error number before you proceed.

Also, when writing your checks, look at shinfo - and specifically see if SHGetFileInfo populates shinfo.hIcon .

You could be passing a NULL to Icon.FromHandle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM