如何在Python中获取桌面项目数量?

5
我正在尝试在Python 2.7中使用win32gui获取桌面上的项目数。

以下代码:win32gui.SendMessage(win32gui.GetDesktopWindow(), LVM_GETITEMCOUNT)返回零,我不知道为什么。

之后我写了win32api.GetLastError(),它也返回了零。

提前感谢你的帮助。

编辑:我需要使用这种方法是因为最终目标是获取图标的位置,而这是通过类似的方法完成的。所以我只是想确保我知道如何使用这种方法。另外,我认为它可以给出与列出桌面内容不同的输出(可以吗?)。第三,我的获取位置的来源建议用这种方法 - 例如http://www.codeproject.com/Articles/639486/Save-and-restore-icon-positions-on-desktop

编辑2:

完整获取计数的代码(对我无效):

import win32gui
from commctrl import LVM_GETITEMCOUNT
print win32gui.SendMessage(win32gui.GetDesktopWindow(), LVM_GETITEMCOUNT)

再次感谢!

解决方案:

import ctypes
from commctrl import LVM_GETITEMCOUNT
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_GETITEMCOUNT)

desktop = get_desktop()
get_item_count(desktop)
1个回答

2
你可以使用os.listdir
import os

len(os.listdir('path/desktop'))

我实际上想要获取图标的位置,而在此之前我需要知道图标的数量。无论如何,我必须使用相同的方法来获取位置。另外,我不确定这些方法是否总是返回相同的输出 - 这是一个好问题。我主要使用这种方法是因为我的来源建议这样做(例如http://www.codeproject.com/Articles/639486/Save-and-restore-icon-positions-on-desktop)。 - Ella Sharakanski
好的,你的问题是如何获取计数,我已经回答了你的问题,编辑和更改问题不是解决问题的方法。 - Padraic Cunningham
我的问题是关于在Python 2.7中使用win32gui。当我发布问题时,我认为我的问题很清楚,后来意识到不够清楚时,我进行了编辑。 - Ella Sharakanski
可能会有用:http://superuser.com/questions/625854/where-does-windows-store-icon-positions - Padraic Cunningham
2
好的,答案在这里的第二个问题中,https://dev59.com/YHI-5IYBdhLWcg3wy70d。`GetDesktopWindow()` 返回的是实际桌面,但你需要使用 FindWindowEx 来访问存储图标的资源管理器桌面。 - Padraic Cunningham
显示剩余11条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接