WTL文件拖拽

Scroll Down

1.对话框属性中把:Accept Files设置为TRUE,或者ModifyStyleEx(0, WS_EX_ACCEPTFILES);

2.在对话框中添加一个ListBox控件,并关联成员变量:m_lstTest;

3.在ListBox属性中同样把:Accept Files设置为TRUE;

4.添加消息响应:

MESSAGE_HANDLER(WM_DROPFILES, OnDropFiles)

LRESULT OnDropFiles(UINT /uMsg/, WPARAM /wParam/, LPARAM /lParam/, BOOL& /bHandled/);

5.实现:

LRESULT CMainDlg::OnDropFiles(UINT /uMsg/, WPARAM wParam, LPARAM /lParam/, BOOL& /bHandled/)

{

HDROP hDrop = (HDROP)wParam;

wchar_t buf[MAX_PATH] = {0};

int nFileCount = DragQueryFile(hDrop, 0xFFFFFFFF, buf, MAX_PATH);//经检MSDN,0xFFFFFFFF返回托拽文件个数

if(nFileCount > 0)

{

for(int i = 0; i < nFileCount; i++)

{

memset(buf, 0, MAX_PATH);

DragQueryFile(hDrop, i, buf, MAX_PATH);

RECT rtTest;

m_lstTest.GetWindowRect(&rtTest);

POINT pt;

GetCursorPos(&pt);

if(::PtInRect(&rtTest, pt))

{

m_lstTest.AddString(buf);

}

}

}

DragFinish(hDrop);

return 0;

}

在实际工作中还会遇到另一个问题,如果编译选项中UAC选择的是requireAdministrator的话(默认是:asInvoker),WIN7中托拽文件不成功,大概原因是低权限无法向高权限发消息引起的问题.

解决方案是(借用别人方法):

typedef BOOL (WINAPI *_ChangeWindowMessageFilter)( UINT , DWORD);

BOOL AllowMeesageForVista(UINT uMessageID, BOOL bAllow)//注册Vista全局消息

{

BOOL bResult = FALSE;

HMODULE hUserMod = NULL;

//vista and later

hUserMod = LoadLibrary( L"user32.dll" );

if( NULL == hUserMod )

{

return FALSE;

}

_ChangeWindowMessageFilter pChangeWindowMessageFilter = (_ChangeWindowMessageFilter)GetProcAddress( hUserMod, "ChangeWindowMessageFilter" );

if( NULL == pChangeWindowMessageFilter )

{

return FALSE;

}

bResult = pChangeWindowMessageFilter( uMessageID, bAllow ? 1 : 2 );//MSGFLT_ADD: 1, MSGFLT_REMOVE: 2

if( NULL != hUserMod )

{

FreeLibrary( hUserMod );

}

return bResult;

}

在OnInitDialog中加入三句:

LRESULT OnInitDialog(UINT /uMsg/, WPARAM /wParam/, LPARAM /lParam/, BOOL& /bHandled/)

{

...

AllowMeesageForVista(WM_DROPFILES, TRUE);

AllowMeesageForVista(WM_COPYDATA, TRUE);

AllowMeesageForVista(0x0049, TRUE);

...

}