如何获取(逻辑)桌面上的项目总数(C#)

时间:2011-09-15 06:48:24

标签: c# windows c#-2.0 desktop special-folders

让我详细说明一下。 “items”我指的是你在桌面上看到的所有项目(Windows),其中包括“我的电脑”,“回收站”,所有快捷方式等。如果我选​​择桌面上的所有项目,我会在属性中获得计数显示。这是我想要的,以编程方式。

我面临的问题:

我们看到的桌面包含我帐户中的项目,All Users的桌面项目以及“我的电脑”,“回收站”等其他快捷方式。总共有3件事。所以我不能只从物理路径到Desktop目录获取项目数。所以这失败了:

int count =
    Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder
                                                            .DesktopDirectory)
                      ).Length;

我知道SpecialFolder.Desktop代表我们看到的逻辑桌面。但是这再次失败,因为GetFolderPath()再次获得用户桌面的物理路径:

int count = 
    Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder
                                                            .Desktop)
                      ).Length;

在用户桌面上获取总计数的正确方法是什么?

3 个答案:

答案 0 :(得分:4)

Windows shell对此提供全面而全面的支持。

  1. 致电SHGetDesktopFolder()获取桌面IShellFolder
  2. 致电IShellFolder::EnumObjects()获取内容。
  3. 这个Code Project article从C#角度提供了一些使用示例。

答案 1 :(得分:-2)

这是不可能以你想要的方式实现的。

你可能忘记了任何桌面上都有元素,这些元素与文件无关(文件或链接),而是基于注册表的,你会明确地错过它们。

答案 2 :(得分:-3)

我正在回答我最后通过这里发布的提示和链接找到的答案。

    private const uint GET_ITEM_COUNT = 0x1000 + 4;



    [DllImport("user32.DLL")]

    private static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

    [DllImport("user32.DLL")]

    private static extern IntPtr FindWindow(string lpszClass, string lpszWindow);

    [DllImport("user32.DLL")]

    private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, 
                                                            string lpszClass, string lpszWindow);



    public static int GetDesktopCount()
    {
        //Get the handle of the desktop listview

        IntPtr vHandle = FindWindow("Progman", "Program Manager");

        vHandle = FindWindowEx(vHandle, IntPtr.Zero, "SHELLDLL_DefView", null);

        vHandle = FindWindowEx(vHandle, IntPtr.Zero, "SysListView32", "FolderView");


        //Get total count of the icons on the desktop

        int vItemCount = SendMessage(vHandle, GET_ITEM_COUNT, 0, 0);

        return vItemCount;
    }

有一个有趣的(相当烦人的)我同时学习的东西。您在屏幕上看到的桌面与桌面的文件夹视图不同。即使您取消选中“我的电脑”和“MyDocument”不在桌面上(您在显示器上看到的桌面),这些图标仍然可以存在于桌面的文件夹视图中。我尝试了这个link中给出的解决方案,但是它给出了文件夹视图中存在的项目数。我上面发布的解决方案将产生我想要的完美结果。解决方案是由叶志新从here得到的。谢谢@ C.Evenhuis的提示。