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

Ell*_*ski 5 python pywin32 win32gui python-2.7

我正在尝试使用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.

EDIT2:

获取计数的完整代码(对我不起作用):

import win32gui
from commctrl import LVM_GETITEMCOUNT
print win32gui.SendMessage(win32gui.GetDesktopWindow(), LVM_GETITEMCOUNT)
Run Code Online (Sandbox Code Playgroud)

再次感谢!

解:

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)
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 2

您可以使用os.listdir

import os

len(os.listdir('path/desktop'))
Run Code Online (Sandbox Code Playgroud)

  • 好的,答案在第二个问题中,http://stackoverflow.com/questions/1669111/how-do-i-get-the-window-handle-of-the-desktop `GetDesktopWindow()` 返回的是实际的桌面,但您需要“FindWindowEx”来访问存储图标的资源管理器桌面 (2认同)