Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 作者: 张赐荣
- # 平台: Windows
- import ctypes
- from ctypes import wintypes
- # <-定义结构体 ->
- # SHQUERYRBINFO 结构体用于接收回收站信息
- # 文档: https://learn.microsoft.com/zh-cn/windows/win32/api/shellapi/ns-shellapi-shqueryrbinfo
- class SHQUERYRBINFO(ctypes.Structure):
- _fields_ = [
- ("cbSize", wintypes.DWORD), # 结构体大小
- ("i64Size", ctypes.c_longlong), # 回收站内文件总大小 (字节)
- ("i64NumItems", ctypes.c_longlong) # 回收站内项目总数
- ]
- # <- 定义常量 ->
- # 文档: https://learn.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-messagebox
- MB_OK = 0x00000000
- MB_ICONINFORMATION = 0x00000040
- MB_ICONWARNING = 0x00000030
- MB_ICONERROR = 0x00000010
- def get_recycle_bin_count():
- """获取所有驱动器回收站的文件总数"""
- shell32 = ctypes.WinDLL('shell32', use_last_error=True)
- # 定义 SHQueryRecycleBinW
- # 文档: https://learn.microsoft.com/zh-cn/windows/win32/api/shellapi/nf-shellapi-shqueryrecyclebinw
- # HRESULT SHQueryRecycleBinW(LPCWSTR pszRootPath, LPSHQUERYRBINFO pSHQueryRBINFO);
- shell32.SHQueryRecycleBinW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(SHQUERYRBINFO)]
- shell32.SHQueryRecycleBinW.restype = ctypes.HRESULT
- rb_info = SHQUERYRBINFO()
- rb_info.cbSize = ctypes.sizeof(SHQUERYRBINFO)
- # pszRootPath 为 None 表示查询所有驱动器
- hr = shell32.SHQueryRecycleBinW(None, ctypes.byref(rb_info))
- if hr == 0:
- return rb_info.i64NumItems
- return -1
- def empty_recycle_bin():
- shell32 = ctypes.WinDLL('shell32', use_last_error=True)
- user32 = ctypes.WinDLL('user32', use_last_error=True)
- # 定义 SHEmptyRecycleBinW
- # 文档: https://learn.microsoft.com/zh-cn/windows/win32/api/shellapi/nf-shellapi-shemptyrecyclebinw
- shell32.SHEmptyRecycleBinW.argtypes = [wintypes.HWND, wintypes.LPCWSTR, wintypes.DWORD]
- shell32.SHEmptyRecycleBinW.restype = ctypes.HRESULT
- # 记录执行前的项目数
- count_before = get_recycle_bin_count()
- if count_before == 0:
- user32.MessageBoxW(None, "回收站已经是空的,无需操作。", "提示", MB_OK | MB_ICONINFORMATION)
- return
- # 调用 API 执行清空 (dwFlags=0, 显示系统确认对话框)
- hr = shell32.SHEmptyRecycleBinW(None, None, 0)
- # 记录执行后的项目数
- count_after = get_recycle_bin_count()
- # 综合判断
- # 逻辑:API必须成功 AND (文件数减少了 OR 文件数变为了0)
- if hr == 0:
- if count_after < count_before and count_after >= 0:
- user32.MessageBoxW(None, f"清空成功!\n文件数从 {count_before} 降至 {count_after}。", "成功", MB_OK | MB_ICONINFORMATION)
- elif count_before != -1 and count_after == count_before:
- # API 返回了成功,但数量没变,说明用户在系统对话框点了“否”
- user32.MessageBoxW(None, "操作已取消或未执行删除。", "提示", MB_OK | MB_ICONWARNING)
- else:
- user32.MessageBoxW(None, "回收站状态未发生显著变化。", "提示", MB_OK | MB_ICONWARNING)
- else:
- # 如果返回了非 0 的 HRESULT
- err_hex = hex(hr & 0xFFFFFFFF)
- user32.MessageBoxW(None, f"操作失败。错误代码: {err_hex}", "错误", MB_OK | MB_ICONERROR)
- if __name__ == "__main__":
- empty_recycle_bin()
Advertisement
Add Comment
Please, Sign In to add comment