|  | 
 
| clistctrl中实现文件拖放接收文件,单文件及多文件代码 以下是CListCtrl实现文件拖放功能的完整解决方案,包含单文件和多文件处理:
 
 使用说明: 在对话框初始化时调用RegisterDropTarget()启用拖放单文件版只处理第一个文件路径多文件版遍历所有拖入文件内存管理需在析构时释放SetItemData分配的内存
 注意事项: DragDropListCtrl.h需在stdafx.h中包含windows.h和shellapi.h项目属性需启用OLE支持建议添加图标显示不同文件类型大数据量时考虑虚拟列表技术优化
 DragDropListCtrl.cpp复制代码
#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();
};
 复制代码 "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[MAX_PATH] = {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[MAX_PATH] = {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);
}
 
 | 
 |