首页 > 解决方案 > 在 Windows 中获取桌面上的选定文件 (7)

问题描述

有人可以告诉我如何在 Python 中获取 Windowsd 桌面上的所有选定文件吗?我一直在寻找一种方法来做到这一点,但我找不到任何人。我发现的唯一一个是用于 C#,但我没有用 C# 编写代码,所以我什至不知道它是否有效:Get list of selected files from Windows Desktop(如果有人理解它并可以解释/转换它,那也将不胜感激)。我发现了一些非常接近的东西,但我只能让它获得选定文件的数量,而不是它们的路径,就像我想要的那样:

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)。提前致谢!

标签: pythonpython-3.xwinapipywin32

解决方案


推荐阅读