今天在使用迅雷软件播放影片时,觉得这个拖拽播放的功能还不错,想着自己能否实现一个具备文件拖拽功能的窗口呢,查看了下MSDN,原来窗口接受文件需要处理WM_DROPFILES消息。
- WM_DROPFILES消息
MSDN中消息的语法:
PostMessage(
(HWND) hWndControl, // handle to destination control
(UINT) WM_DROPFILES, // message ID
(WPARAM) wParam, // = (WPARAM) (HDROP) hDrop;
(LPARAM) lParam // = 0; not used, must be zero
);
参数介绍如下所示
hDrop
A handle to an internal structure describing the dropped files. Pass this handle DragFinish, DragQueryFile, or DragQueryPoint to retrieve information about the dropped files.
lParam
Must be zero.
- CEdit接收文件
首先定义一个CAcceptFileEdit
继承于CEdilt,处理WM_DROPFILES消息,设置CAcceptFileEdit 控件 Accept Files属性设置为TRUE,这点特别重要,否则,以下代码无效, 具体代码实现如下所示: - AcceptFileEdit.h
//
#pragma once
// CAcceptFileEdit
class CAcceptFileEdit : public CEdit
{
DECLARE_DYNAMIC(CAcceptFileEdit)
public:
CAcceptFileEdit();
virtual ~CAcceptFileEdit();
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnDropFiles(HDROP hDropInfo);
};
- AcceptFileEdit.cpp
#include "AcceptFileEdit.h"
// CAcceptFileEdit
IMPLEMENT_DYNAMIC(CAcceptFileEdit, CEdit)
CAcceptFileEdit::CAcceptFileEdit()
{
}
CAcceptFileEdit::~CAcceptFileEdit()
{
}
BEGIN_MESSAGE_MAP(CAcceptFileEdit, CEdit)
ON_WM_DROPFILES()
END_MESSAGE_MAP()
// CAcceptFileEdit message handlers
void CAcceptFileEdit::OnDropFiles(HDROP hDropInfo)
{
// TODO: Add your message handler code here and/or call default
// 被拖拽的文件的文件名
wchar_t szFileName[MAX_PATH + 1];
// 得到被拖拽的文件名
DragQueryFile(hDropInfo, 0, szFileName, MAX_PATH);
// 把文件名显示出来
SetWindowText(szFileName);
CEdit::OnDropFiles(hDropInfo);
}
具备接收拖拽文件的编辑框类就定义好了,这样就可以顺利的拖拽一个文件到编辑框了。具体就不展示效果了。
- CListBox接收文件
- DragFileListBox .h
#pragma once
// CDragFileListBox
class CDragFileListBox : public CListBox
{
DECLARE_DYNAMIC(CDragFileListBox)
public:
CDragFileListBox();
virtual ~CDragFileListBox();
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnDropFiles(HDROP hDropInfo);
};
- DragFileListBox .cpp
#include "DragFileListBox.h"
// CDragFileListBox
IMPLEMENT_DYNAMIC(CDragFileListBox, CListBox)
CDragFileListBox::CDragFileListBox()
{
}
CDragFileListBox::~CDragFileListBox()
{
}
BEGIN_MESSAGE_MAP(CDragFileListBox, CListBox)
ON_WM_DROPFILES()
END_MESSAGE_MAP()
// CDragFileListBox message handlers
void CDragFileListBox::OnDropFiles(HDROP hDropInfo)
{
// TODO: Add your message handler code here and/or call default
//获取文件的个数
int nFileNum = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0);
for (int i = 0; i < nFileNum; i++)
{
wchar_t strFileName[MAX_PATH] = { 0 };
int nres = DragQueryFile(hDropInfo, i, strFileName, MAX_PATH);
if (!this->FindString(0, strFileName))
{
continue;
}
this->AddString(strFileName);
}
CListBox::OnDropFiles(hDropInfo);
}
- 总结
以上为借助CEdit和CListBox类实现两个可接受文件拖拽的类,实现文件拖拽功能控件,必须实现WM_DROPFILES 消息,同时控件必须设置Accept Files 属性为TRUE。