How to get desktop item count in python?

匆匆过客 提交于 2020-01-03 13:55:11

问题


I'm trying to get the number of items on the desktop using win32gui in python 2.7.

The following code: win32gui.SendMessage(win32gui.GetDesktopWindow(), LVM_GETITEMCOUNT) returns zero and I have no idea why.

I wrote win32api.GetLastError() afterwards and it returned zero either.

Thanks in advance.

EDIT: I need to use this method because the final goal is to get the positions of the icons, and it's done by a similar method. So I just wanted to make sure that I know how to use this method. Also, I think that it can give a different output than listing the content of desktop (can it?). And thirdly, my sources of how to get the positions suggested to do it this way - http://www.codeproject.com/Articles/639486/Save-and-restore-icon-positions-on-desktop for example.

EDIT2:

Full code for getting the count (doesn't work for me):

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

Thanks again!

SOLUTION:

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:


You can use os.listdir:

import os

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


来源:https://stackoverflow.com/questions/27663875/how-to-get-desktop-item-count-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!