先介绍下,对对话框需要设置属性:AcceptFile为true;
源码工程:下载
#include <windows.h> #include <ShlObj.h> #include <CommCtrl.h> #include <WindowsX.h> #include "resource.h" LRESULT CALLBACK DialogProc(HWND ,UINT,WPARAM,LPARAM) ; void OnInitDialog(HWND hDlg); void OnOK(HWND hDlg); void HandleDragFile(HWND hDlg, HDROP hDrop); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { MSG msg; HWND hwnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, (DLGPROC)DialogProc); ShowWindow(hwnd, SW_SHOW); UpdateWindow(hwnd); while(GetMessage(&msg, NULL, 0, 0)) { if( !IsDialogMessage( hwnd, &msg ) ) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; } LRESULT CALLBACK DialogProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) { switch(uMsg) { case WM_INITDIALOG: OnInitDialog(hWnd); SetWindowPos(hWnd,NULL,500,200,0,0,SWP_NOSIZE); return TRUE; case WM_DROPFILES: HandleDragFile(hWnd,reinterpret_cast<HDROP>(wParam)); break; case WM_COMMAND: if(LOWORD(wParam) == IDOK) { //OnOK(hWnd); PostQuitMessage(0); return TRUE; } if(LOWORD(wParam) == IDCANCEL) { PostQuitMessage(0); return TRUE; } break; case WM_DESTROY: PostQuitMessage(0); break; } return FALSE; } void OnInitDialog(HWND hDlg) { HWND hwndView = GetDlgItem(hDlg,IDC_VIEW); // RECT rc; DWORD dwStyle = GetWindowStyle(hwndView); SetWindowLong(hwndView, GWL_STYLE, dwStyle | LVS_REPORT); GetClientRect(hwndView, &rc); LV_COLUMN lvc; ZeroMemory(&lvc, sizeof(LV_COLUMN)); lvc.mask = LVCF_TEXT | LVCF_WIDTH; lvc.pszText = TEXT("The Link Path"); lvc.cx = rc.right; ListView_InsertColumn(hwndView, 0, &lvc); //添加一项 } void HandleDragFile(HWND hDlg, HDROP hDrop) { POINT pt; DragQueryPoint(hDrop,&pt); //获取拖拽鼠标点 ClientToScreen(hDlg,&pt); // HWND hwndDrop = WindowFromPoint(pt); //获取拖拽点所在的控件 HWND hwndView = GetDlgItem(hDlg, IDC_VIEW); if(hwndDrop != hwndView) //判断是否在IDC_VIEW控件上 { MessageBox(hDlg,TEXT("Sorry, you have to drop over the list view control!"),TEXT("Message"),MB_OK); return; } LONG count = DragQueryFile(hDrop,-1,NULL,0); //获取拖拽的文件数目 BSTR szFileName = SysAllocStringLen(NULL,MAX_PATH); //分配字符串 // LV_ITEM lvi; ZeroMemory(&lvi, sizeof(LV_ITEM)); for (int i=0; i<count; i++) { DragQueryFile(hDrop,i,szFileName,MAX_PATH); //获取路径名 lvi.mask = LVIF_TEXT; //增加一项 lvi.pszText = szFileName; lvi.cchTextMax = lstrlen(szFileName); lvi.iItem = 0; ListView_InsertItem(hwndView, &lvi); } } void OnOK(HWND hDlg) { }