在Windows中显示文件的资源管理器属性对话框
有没有简单的方法可以用Python在Windows中显示一个文件的属性对话框?
我想要显示和在资源管理器中右键点击一个文件后选择“属性”时弹出的那个窗口是一样的。
1 个回答
7
要实现这个功能,你需要调用Windows的ShellExecuteEx()
这个API,并传入properties
这个参数。虽然有很多高级的Python封装可以使用,但我尝试过的都没能成功与properties
一起工作。所以我建议使用老牌的ctypes
库。
import time
import ctypes
import ctypes.wintypes
SEE_MASK_NOCLOSEPROCESS = 0x00000040
SEE_MASK_INVOKEIDLIST = 0x0000000C
class SHELLEXECUTEINFO(ctypes.Structure):
_fields_ = (
("cbSize",ctypes.wintypes.DWORD),
("fMask",ctypes.c_ulong),
("hwnd",ctypes.wintypes.HANDLE),
("lpVerb",ctypes.c_char_p),
("lpFile",ctypes.c_char_p),
("lpParameters",ctypes.c_char_p),
("lpDirectory",ctypes.c_char_p),
("nShow",ctypes.c_int),
("hInstApp",ctypes.wintypes.HINSTANCE),
("lpIDList",ctypes.c_void_p),
("lpClass",ctypes.c_char_p),
("hKeyClass",ctypes.wintypes.HKEY),
("dwHotKey",ctypes.wintypes.DWORD),
("hIconOrMonitor",ctypes.wintypes.HANDLE),
("hProcess",ctypes.wintypes.HANDLE),
)
ShellExecuteEx = ctypes.windll.shell32.ShellExecuteEx
ShellExecuteEx.restype = ctypes.wintypes.BOOL
sei = SHELLEXECUTEINFO()
sei.cbSize = ctypes.sizeof(sei)
sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_INVOKEIDLIST
sei.lpVerb = "properties"
sei.lpFile = "C:\\Desktop\\test.txt"
sei.nShow = 1
ShellExecuteEx(ctypes.byref(sei))
time.sleep(5)
我在这里加上sleep
的调用是因为属性对话框会作为一个窗口显示在调用的进程中。如果Python程序在调用ShellExecuteEx
后立刻结束,那么就没有东西来处理这个对话框,它就不会显示出来。