使用拖放的简单方法
如果要为窗口增加接受Drag&Drop的功能,请按照以下步骤:
1、在OnCreate(...)中调用AcceptDrag(TRUE)。
2、增加消息映射
BEGIN_MESSAGE_MAP(……)
//{{AFX_MSG_MAP(CDropEdit)
ON_WM_CREATE()
ON_WM_DROPFILES() // 关于Drag&Drop的消息
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
3、处理消息
void CXXXXX::OnDropFiles(HDROP dropInfo)
{
// 得到Drag&Drop的文件个数
WORD wNumFilesDropped = DragQueryFile(dropInfo, -1, NULL, 0);
CString firstFile="";
//
for (WORD x = 0 ; x < wNumFilesDropped; x++) {
// 得到PathName的长度,由于第三个参数为NULL,所以调用会失败并返回所需长度
WORD wPathnameSize = DragQueryFile(dropInfo, x, NULL, 0);
// 分配memory
char * npszFile = (char *) LocalAlloc(LPTR, wPathnameSize += 1);
// 分配错
if (npszFile == NULL) continue;
// 再次得到文件名
DragQueryFile(dropInfo, x, npszFile, wPathnameSize);
firstFile=npszFile;
// 如果是shortCut则进行转换得到正确的文件名,expandedFile为最后的文件名
CString expandedFile = ExpandShortcut(firstFile);
// 释放memory
LocalFree(npszFile);
}
//完成
DragFinish(dropInfo);
}
4、关于ExpandShortcut(...)
CString CXXXXX::ExpandShortcut(CString &inFile)
{
CString outFile = "";
// Make sure we have a path
ASSERT(inFile != _T(""));
IShellLink* psl;
HRESULT hres;
LPTSTR lpsz = inFile.GetBuffer(MAX_PATH);
// Create instance for shell link
hres = ::CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
IID_IShellLink, (LPVOID*) &psl);
if (SUCCEEDED(hres))
{
// Get a pointer to the persist file interface
IPersistFile* ppf;
hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*) &ppf);
if (SUCCEEDED(hres))
{
// Make sure it's ANSI
WORD wsz[MAX_PATH];
::MultiByteToWideChar(CP_ACP, 0, lpsz, -1, wsz, MAX_PATH);
// Load shortcut
hres = ppf->Load(wsz, STGM_READ);
if (SUCCEEDED(hres)) {
WIN32_FIND_DATA wfd;
// find the path from that
HRESULT hres = psl->GetPath(outFile.GetBuffer(MAX_PATH),
MAX_PATH,
&wfd,
SLGP_UNCPRIORITY);
outFile.ReleaseBuffer();
}
ppf->Release();
}
psl->Release();
}
inFile.ReleaseBuffer();
// if this fails, outFile == ""
return outFile;
}
摘自玉海园 http://www.mfc2000.yeah.net
本文地址:http://com.8s8s.com/it/it3776.htm