需要重载类的WM_DROPFILE消息。
接受拖放的文件并显示路径与文件名的示例:
void CYuEdit::OnDropFiles(HDROP hDropInfo)
{
// TODO: Add your message handler code here and/or call default
UINT nFilesDroppedCount = DragQueryFile(hDropInfo, -1, NULL, 0); //同时拖放的文件数目
CString firstFileStr = NULL;
for (UINT x = 0; x < nFilesDroppedCount; x++)
{
UINT nPathNamesize = DragQueryFile(hDropInfo, x, NULL, 0);
LPWSTR lpwstrFile = (LPWSTR)LocalAlloc(LPTR, nPathNamesize += 1); //分配内存
if (lpwstrFile == NULL) continue;
DragQueryFile(hDropInfo, x, lpwstrFile, nPathNamesize); //获取拖放的路径及文件名
if (firstFileStr == _T(""))
{
firstFileStr = lpwstrFile; //记录文件名
}
LocalFree(lpwstrFile); //释放内存
}
DragFinish(hDropInfo); //拖放结束
SetWindowText(firstFileStr); //编辑框显示
//CEdit::OnDropFiles(hDropInfo);
}
注意要设置控件的Accept Files属性为
TRUE。