[英]Getting Icon Of Special Folders Such As My Computer And Libraries
我一直試圖構造一個類來簡單地獲取特殊文件夾的當前圖標,例如“我的電腦”,“計算機”,“庫”等。我目前正在嘗試使用SHGetFileInfo()API來實現此目的。
Microsoft頁面上的原始SHGetFileInfo函數...
#1代碼塊
DWORD_PTR SHGetFileInfo(
_In_ LPCTSTR pszPath,
DWORD dwFileAttributes,
_Inout_ SHFILEINFO *psfi,
UINT cbFileInfo,
UINT uFlags
);
(以上引用自: http : //msdn.microsoft.com/zh-cn/library/windows/desktop/bb762179%28v=vs.85%29.aspx )
在另一個SO問題上,我找到了一個例子...
#2代碼塊
IntPtr pidl;
SHGetSpecialFolderLocation(0, CSIDL_DRIVES, pidl);
SHGetFileInfo(pidl, 0, shinfo, Marshal.SizeOf(shinfo), (SHGFI_PIDL | SHGFI_DISPLAYNAME | SHGFI_ICON | SHGFI_SMALLICON));
(以上引用自: https : //stackoverflow.com/a/14293350/1039753 )
這說明以要求第一個參數為IntPtr的方式使用SHGetFileInfo。 我的印象是第一個參數必須是基於此的字符串...
#3代碼塊
[DllImport("shell32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);
(以上引用來自: http : //pinvoke.net/default.aspx/shell32.SHGetFileInfo )
此外,環顧四周,我也找到了這個答案...
#4代碼塊
[DllImport("Pdh.dll")]
static extern int PdhOpenQueryW(
[MarshalAs(UnmanagedType.LPWStr)] string szDataSource,
UIntPtr dwUserData,
out IntPtr phQuery);
(以上引用自: https : //stackoverflow.com/a/3598417/1039753 )
在上面的答案中,用戶告訴原始海報使用...
#5代碼塊
[MarshalAs(UnmanagedType.LPWStr)] string
映射到
#6代碼塊
"_In_ LPCTSTR pszPath,"
參數。 在頂部的MSDN c ++構造函數中找到。 對我來說,這比任何一個都有意義。 但是我無法確定的是上面的答案(#2代碼塊),當pinvoke.net網站說將其定義為字符串時,該答案告訴原始發布者使用IntPtr。
知道如何使SHGetFileInfo()起作用來獲取該圖標嗎? 謝謝!
更新
這是我嘗試使用它的示例...
[DllImport("Shell32.dll")]
public static extern IntPtr SHGetFileInfo(
string pszPath,
uint dwFileAttributes,
ref SHFILEINFO psfi,
uint cbFileInfo,
uint uFlags
);
SHGetFileInfo((IntPtr)oTarget, 0, ref shfi, (uint)Marshal.SizeOf(shfi), flags);
然后我得到兩個錯誤...
Error 1 The best overloaded method match for 'SHGetFileInfo(string, uint, ref SHFILEINFO, uint, uint)' has some invalid arguments C:\FakePath\ImageWorker.cs 67 25 ImageWorker
Error 2 Argument 1: cannot convert from 'System.IntPtr' to 'string' C:\FakePath\ImageTool.cs 67 47 ImageWorker
如何獲得圖標示例:
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
public string szDisplayName;
public string szTypeName;
};
SHFILEINFO shinfo= new SHFILEINFO();
SHGetFileInfo(@"...", 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), 0x000000100); //SHGFI_ICON
Icon icon = (Icon)Icon.FromHandle(shinfo.hIcon);
//use the icon and finally destroy it with:
DestroyIcon(shinfo.hIcon);
SHGetFileInfo
很時髦。 第一個參數是指向以null終止的字符數組的指針,或者是PIDL。 在非托管代碼中,該參數聲明為以null終止的字符數組。 如果要通過PIDL,則應執行強制轉換。
在ap / invoke通話中,您不能使用強制轉換。 因此,您需要聲明兩個重載的p / invoke導入。 一個使用string
作為第一個參數,另一個使用IntPtr
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.