DragQueryFiles can't obtain the file path

383 Views Asked by At

My code:

void CWGAccountFilterDlg::OnDropFiles(HDROP hDropInfo)
{
    // TODO: 在此添加消息处理程序代码和/或调用默认值
    CDialogEx::OnDropFiles(hDropInfo);
    wchar_t lpFilePath[MAX_PATH] = { 0 };
    int nCount = DragQueryFile(hDropInfo, -1, NULL, 0);
    DragQueryFile(hDropInfo, nCount, lpFilePath, _countof(lpFilePath));
    DragFinish(hDropInfo);
    GetDlgItem(IDC_EDIT_FILE)->SetWindowText(lpFilePath);
    m_FilePath.Format(L"%s", lpFilePath);
}

The 2nd calling of DragQueryFile returns 0 (this situation is correct) and lpFilePath (this is not the expect) has no data in it. I'm sure that the nCount value is valid, no buffer overflow.

The dialog and the CEdit control all set 'accept files' to true. And there is a class named CMyEdit implement from CEdit, and processed the OnDropFiles function.

1

There are 1 best solutions below

1
On

From documentation for DragQueryFileW:

Index of the file to query. If the value of this parameter is 0xFFFFFFFF, DragQueryFile returns a count of the files dropped. If the value of this parameter is between zero and the total number of files dropped, DragQueryFile copies the file name with the corresponding value to the buffer pointed to by the lpszFile parameter.

In the second call to DragQueryFile, the second parameter should be between 0 and nCount. Test the value for nCount to make sure it is greater than zero, and pass zero if you are only interested in the first file.

This assumes there is only one file being dropped. If there are more files, then add a loop.

int nCount = DragQueryFile(hDropInfo, -1, NULL, 0);
if (nCount > 0)
{
    //(add a loop to get multiple files)
    DragQueryFile(hDropInfo, 0, lpFilePath, _countof(lpFilePath));
    GetDlgItem(IDC_EDIT_FILE)->SetWindowText(lpFilePath);
    m_FilePath.Format(L"%s", lpFilePath);
}
DragFinish(hDropInfo);