有人可以告诉我如何用Python获取Windowsd桌面上所有选定的文件吗?我一直在寻找一种方法来做到这一点,但找不到任何人。我找到的唯一一个是针对 C# 的,但我没有用 C# 编写代码,所以我什至不知道它是否有效:从 Windows 桌面获取所选文件的列表(如果有人理解它并且可以解释/转换它) ,那也将不胜感激)。我发现了与此非常接近的东西,但我只能让它获取所选文件的数量,而不是它们的路径,如我所愿:
import ctypes
from commctrl import LVM_GETITEMCOUNT,LVM_GETSELECTEDCOUNT
#The LVM_GETITEMCOUNT came with the script, I got the other one from Microsoft documentation about SendMessage(), and both are near, but none returns the paths, only numbers
import pywintypes
import win32gui
GetShellWindow = ctypes.windll.user32.GetShellWindow
def get_desktop():
"""Get the window of the icons, the desktop window contains this window"""
shell_window = GetShellWindow()
shell_dll_defview = win32gui.FindWindowEx(shell_window, 0, "SHELLDLL_DefView", "")
if shell_dll_defview == 0:
sys_listview_container = []
try:
win32gui.EnumWindows(_callback, sys_listview_container)
except pywintypes.error as e:
if e.winerror != 0:
raise
sys_listview = sys_listview_container[0]
else:
sys_listview = win32gui.FindWindowEx(shell_dll_defview, 0, "SysListView32", "FolderView")
return sys_listview
def _callback(hwnd, extra):
class_name = win32gui.GetClassName(hwnd)
if class_name == "WorkerW":
child = win32gui.FindWindowEx(hwnd, 0, "SHELLDLL_DefView", "")
if child != 0:
sys_listview = win32gui.FindWindowEx(child, 0, "SysListView32", "FolderView")
extra.append(sys_listview)
return False
return True
def get_item_count(window):
return win32gui.SendMessage(window, LVM_GETSELECTEDCOUNT)
desktop = get_desktop()
print(get_item_count(desktop))
我搜索了可以发送到窗口的命令,但没有找到任何人来获取所选项目的路径(也许我错过了一个?)。
我发现从 Windows 资源管理器窗口获取所选文件的方法,但现在从桌面:https://stackoverflow.com/a/21250927/8228163.
非常感谢任何帮助(任何 Windows,最好是 7)。预先感谢!
我的帖子似乎提供了一种在桌面上获取选定文件的方法,但我现在想到的是如何在文件选择对话框中获取文件。