clistctrl中实现文件拖放接收文件,单文件及多文件代码
clistctrl中实现文件拖放接收文件,单文件及多文件代码以下是CListCtrl实现文件拖放功能的完整解决方案,包含单文件和多文件处理:
使用说明:
[*]在对话框初始化时调用RegisterDropTarget()启用拖放
[*]单文件版只处理第一个文件路径
[*]多文件版遍历所有拖入文件
[*]内存管理需在析构时释放SetItemData分配的内存
注意事项:
[*]需在stdafx.h中包含windows.h和shellapi.h
[*]项目属性需启用OLE支持
[*]建议添加图标显示不同文件类型
[*]大数据量时考虑虚拟列表技术优化
DragDropListCtrl.h
#pragma once
#include <afxcview.h>
#include <afxole.h>
class CDragDropListCtrl : public CListCtrl
{
public:
DECLARE_DYNAMIC(CDragDropListCtrl)
CDragDropListCtrl();
virtual ~CDragDropListCtrl();
protected:
CImageList m_DropTargetImage;
BOOL RegisterDropTarget();
DECLARE_MESSAGE_MAP()
afx_msg void OnDropFiles(HDROP hDropInfo);
afx_msg void OnDestroy();
};
DragDropListCtrl.cpp
"stdafx.h"
#include "DragDropListCtrl.h"
IMPLEMENT_DYNAMIC(CDragDropListCtrl, CListCtrl)
BEGIN_MESSAGE_MAP(CDragDropListCtrl, CListCtrl)
ON_WM_DROPFILES()
ON_WM_DESTROY()
END_MESSAGE_MAP()
CDragDropListCtrl::CDragDropListCtrl()
{
m_DropTargetImage.Create(1, 22, ILC_COLOR, 0, 1);
}
BOOL CDragDropListCtrl::RegisterDropTarget()
{
return DragAcceptFiles(TRUE);
}
void CDragDropListCtrl::OnDestroy()
{
DragAcceptFiles(FALSE);
CListCtrl::OnDestroy();
}
// 单文件处理版本
void CDragDropListCtrl::OnDropFiles_Single(HDROP hDropInfo)
{
TCHAR szFilePath = {0};
UINT nCount = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0);
if(nCount == 1) {
DragQueryFile(hDropInfo, 0, szFilePath, MAX_PATH);
int nIndex = InsertItem(GetItemCount(), szFilePath);
SetItemData(nIndex, (DWORD_PTR)new CString(szFilePath));
}
DragFinish(hDropInfo);
}
// 多文件处理版本
void CDragDropListCtrl::OnDropFiles_Multi(HDROP hDropInfo)
{
TCHAR szFilePath = {0};
UINT nCount = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0);
for(UINT i = 0; i < nCount; ++i) {
DragQueryFile(hDropInfo, i, szFilePath, MAX_PATH);
int nIndex = InsertItem(GetItemCount(), szFilePath);
SetItemData(nIndex, (DWORD_PTR)new CString(szFilePath));
}
DragFinish(hDropInfo);
}
页:
[1]