C++与资源管理器交互,获取剪贴板复制的文件路径
#include <oleidl.h>
#include <comdef.h>
#include <vector>
#include <string>
std::vector<std::string> GetPaths()
{
std::vector<std::string> path_list;
if (::OpenClipboard(NULL)) // 打开剪切板
{
HDROP hDrop = HDROP(::GetClipboardData(CF_HDROP)); // 获取剪切板中复制的文件列表相关句柄
if (hDrop != NULL)
{
WCHAR szFilePathName[MAX_PATH + 1] = { 0 };
UINT nNumOfFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0); // 得到文件个数
// 考虑到用户可能同时选中了多个对象(可能既包含文件也包含文件夹),所以要循环处理
for (UINT nIndex = 0; nIndex < nNumOfFiles; ++nIndex)
{
memset(szFilePathName, 0, MAX_PATH + 1);
DragQueryFile(hDrop, nIndex, szFilePathName, MAX_PATH); // 得到文件名
_bstr_t path(szFilePathName);
std::string ss = (LPCSTR)path;
path_list.push_back(ss);
}
}
::CloseClipboard(); // 关闭剪切板
}
return path_list;
}
在Qt中调用实例:
void Test()
{
std::vector<std::string> path_list = getPath();
for each(auto path in path_list)
{
qDebug() << QString(QString::fromLocal8Bit(path.c_str()));
}
}