Windows API遍历桌面上所有文件

要获取桌面上的图标,可以使用Windows API中的Shell API。以下是遍历桌面上所有文件的示例代码:

cpp 复制代码
#include <Windows.h>
#include <ShlObj.h>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // 获取桌面文件夹的路径
    wchar_t desktopPath[MAX_PATH];
    if (FAILED(SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0, desktopPath)))
    {
        cout << "Failed to get desktop folder path." << endl;
        return 1;
    }

    // 获取桌面上的图标
    vector<wstring> icons;

    WIN32_FIND_DATAW findData;
    HANDLE hFind = FindFirstFileW((wstring(desktopPath) + L"\\*").c_str(), &findData);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                continue;

            wstring iconPath = wstring(desktopPath) + L"\\" + findData.cFileName;
            icons.push_back(iconPath);
        } while (FindNextFileW(hFind, &findData));

        FindClose(hFind);
    }

    // 输出桌面图标路径
    for (const auto& icon : icons)
    {
        wcout << icon << endl;
    }

    return 0;
}

在这个示例中,通过调用`SHGetFolderPathW`函数来获取桌面文件夹的路径。然后使用`FindFirstFileW`和`FindNextFileW`遍历桌面上的所有文件和文件夹。我们只对文件感兴趣,所以在循环中排除了文件夹。最后,我们将每个图标的路径存储在一个向量中,并将其输出到控制台。

请注意,此示例代码需要链接Shell32.lib库。

相关推荐
张世争3 小时前
armcc5 c++98 的静态库裁剪大小的方法
windows·静态库·裁剪·armcc
vsropy3 小时前
安装虚拟机VMware
linux·windows
AI行业学习3 小时前
CC‑Switch v3.16.1-下载、配置、安装(2026‑06‑01 最新官方版)
开发语言·人工智能·windows·python
Meaauf3 小时前
Windows11关闭VBS的方法合集
windows
記億揺晃着的那天3 小时前
Windows 通过 Java 获取可用端口的一个坑:Hyper-V 保留端口导致 UDP 绑定失败
java·windows·udp
8Qi83 小时前
Windows 系统Claude Code安装与使用笔记
windows·笔记·agent·claudecode
c_lb72884 小时前
期货量化策略从 Windows 迁到 Linux 服务器:环境注意点
linux·服务器·windows·python
骑士雄师4 小时前
18.1 星系案例:多智能体宇宙探索系统(学习langgraph 的存储知识)
windows·python·学习
韭菜钟4 小时前
Windows下编译coal
windows
crack_comet5 小时前
修复 Claude Code TypeScript LSP 在 Windows 上启动失败的问题
windows·typescript·里氏替换原则