Created
October 20, 2025 16:12
-
-
Save amnweb/5c0b6e3dfe7b62753383d5bce0628208 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def get_stock_icon(icon_id: int) -> Image.Image | None: | |
| """Get a Windows stock icon by its SHSTOCKICONID value. | |
| Args: | |
| icon_id: Stock icon ID from SHSTOCKICONID enum | |
| Example values: | |
| - 31 (SIID_RECYCLER): Empty recycle bin | |
| - 32 (SIID_RECYCLERFULL): Full recycle bin | |
| See: https://learn.microsoft.com/en-us/windows/win32/api/shellapi/ne-shellapi-shstockiconid | |
| Returns: | |
| PIL Image of the stock icon, or None if retrieval fails | |
| """ | |
| try: | |
| import ctypes | |
| from ctypes import wintypes | |
| class SHSTOCKICONINFO(ctypes.Structure): | |
| _fields_ = [ | |
| ("cbSize", wintypes.DWORD), | |
| ("hIcon", wintypes.HICON), | |
| ("iSysImageIndex", ctypes.c_int), | |
| ("iIcon", ctypes.c_int), | |
| ("szPath", wintypes.WCHAR * 260), | |
| ] | |
| # SHGSI flags - must include SHGSI_ICON to request icon handle | |
| SHGSI_ICON = 0x000000100 # Return icon handle (required) | |
| SHGSI_LARGEICON = 0x000000000 # Large icon (default size) | |
| # Must use SHGSI_ICON to get icon handle, combined with size preference | |
| flags = SHGSI_ICON | SHGSI_LARGEICON | |
| sii = SHSTOCKICONINFO() | |
| sii.cbSize = ctypes.sizeof(sii) | |
| # Get the stock icon | |
| result = ctypes.windll.shell32.SHGetStockIconInfo(icon_id, flags, ctypes.byref(sii)) | |
| if result != 0 or not sii.hIcon: | |
| return None | |
| try: | |
| # Convert HICON to PIL Image using existing helper | |
| icon_img = hicon_to_image(sii.hIcon) | |
| return icon_img | |
| finally: | |
| try: | |
| win32gui.DestroyIcon(sii.hIcon) | |
| except Exception: | |
| pass | |
| except Exception as e: | |
| logging.error(f"Error getting stock icon {icon_id}: {e}") | |
| return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment