使用过QQ的人都知道,只要把文件拖拽到消息框中就可以传送文件了。那么这种功能是如何实现的呢?其实很简单,只需要响应一个WM_DROPFILES消息就可以了。
在基于对话框的程序中,默认是没有这个消息的,按下Ctrl+W,弹出类向导对话框,选择Class Info标签,在Message fileter下拉列表中选择Window,然后再点击Message Maps标签,就出现WM_DROPFILES消息了,添加该消息的响应函数:
void CTestDlg::OnDropFiles(HDROP hDropInfo)
{
// TODO: Add your message handler code here and/or call default
CDialog::OnDropFiles(hDropInfo);
}
另外,要让对话框能够接受文件拖拽,还需要设置对话框属性。在对话框上点击右键,选择Properties->Extended Styles,点选Accept files选项即可。
要获得当前拖拽的文件的完整文件名(含路径),只需要一个函数:
UINT DragQueryFile(
HDROP hDrop,
UINT iFile,
LPTSTR lpszFile,
UINT cch
);
参数解释:
hDrop: HDROP标识符,即响应函数中的hDropInfo参数
iFile: 待查询的文件索引号,从0开始。可以同时拖拽多个文件,因此就需要一个索引号来进行区分。如果该参数为0xFFFFFFFF,则该函数返回拖拽的文件的个数
lpszFile: 用于存放文件名的缓冲区首地址
cch: 缓冲区长度
返回值:文件名长度
另外,查询完成后需要释放系统分配内存,使用下面这个函数:
VOID DragFinish(
HDROP hDrop
);
下面是一个完整的代码示例,将文件拖拽到对话框上后会弹出消息框显示完整文件名:
void CTestDlg::OnDropFiles(HDROP hDropInfo)
{
// TODO: Add your message handler code here and/or call default
UINT count;
char filePath[200];
count = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0);
if(count)
{
for(UINT i=0; i<count; i++)
{
int pathLen = DragQueryFile(hDropInfo, i, filePath, sizeof(filePath));
AfxMessageBox(filePath);
}
}
DragFinish(hDropInfo);
CDialog::OnDropFiles(hDropInfo);
}
同理,如果只有把文件拖拽到特定的控件中时才有响应,只需要把该控件的Accept files样式勾选上即可。
------------------------------------------------------------------------------------------
把文件拖放到一个程序窗口里打开是一种十分普遍的方法。在MFC中可以通过如下方式实现:
1. 在Mainframe里面 响应WM_CREATE消息,也就是OnCreate里面,加入DragAcceptFiles(TRUE)
2. 在Mainframe里面 添加对WM_DROPFILES消息的响应函数OnDropFiles
3. 在OnDropFiles函数中调用API函数DragQueryFile来检索被拖放文件的名字
具体代码如下:
void CMainFrame::OnDropFiles(HDROP hDropInfo)
{
const int fileCount = DragQueryFile(hDropInfo, (UINT)-1, NULL, 0);
ASSERT(fileCount >= 1);
TCHAR fileName[MAX_PATH] = { 0 };
for (int i = 0; i < fileCount; ++i)
{
DragQueryFile(hDropInfo, i, fileName, MAX_PATH);
//OpenFile(fileName); //使用得到的文件名fileName
}
CFrameWnd::OnDropFiles(hDropInfo); //因为这句,无需使用DragFinish(hDropInfo) 释放检索
}
-----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "iHairSeg.h"
#include "MainFrm.h"
#include "iHairSegDoc.h"
#include "iHairSegView.h"
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
ON_WM_DROPFILES()
END_MESSAGE_MAP()
DragAcceptFiles(TRUE);
CiHairSegView *pViewWnd = (CiHairSegView*)GetActiveView();
pViewWnd->filename = filePath;
int result = MessageBox((LPCTSTR)_T("is a front face photo?"),(LPCTSTR)_T("Warning!"),MB_YESNO);
if (result == IDNO) {
pViewWnd->OnOpenfile2();
} else {
pViewWnd->OnFileOpen();
}
pViewWnd->filename = NULL;