我正在嘗試為 winform 中的串列視圖提取檔案夾圖示。我正在使用[Drawing.Icon]::ExtractAssociatedIcon檔案圖示,但它不適用于檔案夾。我在堆疊上發現了這個問題,它說使用SHGetStockIconInfo,但我不知道如何加載這個函式并在 Powershell 中使用它(我沒有 C 編程經驗)。我設法從鏈接的問題中提取了這個,但我被困住了:
Add-Type -NameSpace WinAPI -Name DefaultIcons -MemberDefinition @'
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHSTOCKICONINFO {
public uint cbSize;
public IntPtr hIcon;
public int iSysIconIndex;
public int iIcon;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szPath;
}
[DllImport("shell32.dll")]
public static extern int SHGetStockIconInfo(uint siid, uint uFlags, ref SHSTOCKICONINFO psii);
[DllImport("user32.dll")]
public static extern bool DestroyIcon(IntPtr handle);
private const uint SHSIID_FOLDER = 0x3;
private const uint SHGSI_ICON = 0x100;
private const uint SHGSI_LARGEICON = 0x0;
private const uint SHGSI_SMALLICON = 0x1;
'@
這運行沒有錯誤,但這是我所能得到的,我不完全理解發生了什么。我知道我需要SHGetStockIconInfo使用三個引數呼叫該函式:
- uint 來識別我想要的圖示
- 我想要的圖示大小的 uint 標志
- 對 SHSTOCKICONINFO 結構的參考
我從中得到所有這些的問題包括一個GetStockIcon函式定義,但我一直在嘗試將它包含在內時遇到錯誤說The type or namespace name 'Icon' could not be found (are you missing a using directive or an assembly reference?)
uj5u.com熱心網友回復:
通過一些調整,我從那個C# 問題中得到了在 PowerShell 5.1 和 7.2.6 下作業的代碼。
$refAsm = if( $PSVersionTable.PSVersion.Major -le 5 ) {'System.Drawing'} else {'System.Drawing.Common'}
Add-Type -ReferencedAssemblies $refAsm -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
using System.Drawing;
public static class DefaultIcons
{
public static Icon GetStockIcon(uint type, uint size)
{
var info = new SHSTOCKICONINFO();
info.cbSize = (uint)Marshal.SizeOf(info);
SHGetStockIconInfo(type, SHGSI_ICON | size, ref info);
var icon = (Icon)Icon.FromHandle(info.hIcon).Clone(); // Get a copy that does not use the original handle
DestroyIcon(info.hIcon); // Clean up native icon to prevent resource leak
return icon;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHSTOCKICONINFO
{
public uint cbSize;
public IntPtr hIcon;
public int iSysIconIndex;
public int iIcon;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szPath;
}
[DllImport("shell32.dll")]
public static extern int SHGetStockIconInfo(uint siid, uint uFlags, ref SHSTOCKICONINFO psii);
[DllImport("user32.dll")]
public static extern bool DestroyIcon(IntPtr handle);
public const uint SHSIID_FOLDER = 0x3;
public const uint SHGSI_ICON = 0x100;
public const uint SHGSI_LARGEICON = 0x0;
public const uint SHGSI_SMALLICON = 0x1;
}
'@
像這樣使用它:
$folderIconLarge = [DefaultIcons]::GetStockIcon( [DefaultIcons]::SHSIID_FOLDER, [DefaultIcons]::SHGSI_LARGEICON )
$folderIconSmall = [DefaultIcons]::GetStockIcon( [DefaultIcons]::SHSIID_FOLDER, [DefaultIcons]::SHGSI_SMALLICON )
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524882.html
上一篇:如何在SQL中計算上標值
