让程序支持拖拽功能

这里主要是三个函数一个消息。三个函数分别是:
[color=#FF0000]VOID DragAcceptFiles(HWND hWnd,BOOL fAccept);
UINT DragQueryFile(HDROP hDrop,UINT iFile,LPTSTR lpszFile,UINT cch);
VOID DragFinish(HDROP hDrop);[/color]

一个消息是:
[color=#FF0000]WM_DROPFILES
SendMessage( hWndControl, WM_DROPFILES, wParam,  lParam ); [/color]
其中:
wParam的值为(HDROP),而lParam的值则必须为0!

由于DragAcceptFiles函数的第一个参数是一个窗口的句柄,所以在创建对话框时,不能用DialogBox、DialogBoxIndirect 、DialogBoxIndirectParam、DialogBoxParam等函数了,可以选择是对应的几个Create系列函数:CreateDialog、CreateDialogIndirect、CreateDialogIndirectParam、CreateDialogParam,因为这几个函数返回的值就是窗口句柄!

主函数的代码如下:


int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE,LPSTR lpCmdLine,int nShowCmd)
{
  g_hInst=hInstance;
  g_hWnd=CreateDialog(g_hInst,MAKEINTRESOURCE(IDD_MAIN),NULL,MyMainProc);
  ShowWindow(g_hWnd,nShowCmd);
  DragAcceptFiles(g_hWnd,TRUE);

  MSG uMsg;
  while(GetMessage(&uMsg,NULL,0,0)){
    TranslateMessage(&uMsg);
    DispatchMessage(&uMsg);
  }

  return 0;
}

接下来就是接收WM_DROPFILES消息并给予处理了:
case WM_DROPFILES:
接收到消息后,将wParam参数传递给DragQueryFile函数进行处理就可以得到我们需要的了:


TCHAR szFilePath[MAX_PATH] = {0};
DragQueryFile((HDROP)wParam,0,szFilePath,MAX_PATH-1);
DragFinish((HDROP)wParam);         //事后清理

一个简单的处理代码如下:


case WM_DROPFILES:
      {
      TCHAR szFilePath[MAX_PATH] = {0};
      memset(szFilePath,0,MAX_PATH);
      DragQueryFile((HDROP)wParam,0,szFilePath,MAX_PATH-1);
      DragFinish((HDROP)wParam);
      SetDlgItemText(hDlg,IDC_DISP,szFilePath);
      return FALSE;
      }

完整的代码如下:


#include
#include
#include"resource.h"

HINSTANCE g_hInst;
HWND g_hWnd;
INT_PTR CALLBACK MyMainProc(HWND,UINT,WPARAM,LPARAM);

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE,LPSTR lpCmdLine,int nShowCmd)
{
  g_hInst=hInstance;
  g_hWnd=CreateDialog(g_hInst,MAKEINTRESOURCE(IDD_MAIN),NULL,MyMainProc);
  ShowWindow(g_hWnd,nShowCmd);
  DragAcceptFiles(g_hWnd,TRUE);

  MSG uMsg;
  while(GetMessage(&uMsg,NULL,0,0)){
    TranslateMessage(&uMsg);
    DispatchMessage(&uMsg);
  }

  return 0;
}

INT_PTR CALLBACK MyMainProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
  switch(uMsg){
    case WM_INITDIALOG:
      SetDlgItemText(hDlg,IDC_DISP,TEXT("直接拖拽文件到这里"));
      return TRUE;
    case WM_SYSCOMMAND:
      switch(wParam)
      {
        case SC_CLOSE:
          DestroyWindow(hDlg);
          PostQuitMessage(0);
          return TRUE;
      }
      return FALSE;

    case WM_DROPFILES:
      {
      TCHAR szFilePath[MAX_PATH] = {0};
      memset(szFilePath,0,MAX_PATH);
      DragQueryFile((HDROP)wParam,0,szFilePath,MAX_PATH-1);
      DragFinish((HDROP)wParam);
      SetDlgItemText(hDlg,IDC_DISP,szFilePath);
      return FALSE;
      }
  }
  return FALSE;
}

编译运行如图:

附件为测试的小程序完整的VS2008工程:
AppDragFile.rar

发表评论