How to find the names of all files from the clipboard

I just created an MFC application to find file names from a clip board

AddClipboardFormatListener(AfxGetApp()->m_pMainWnd->m_hWnd);

LRESULT Cfile_trackerDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
    case WM_CLIPBOARDUPDATE:
        {
            AfxBeginThread(FileArrival, NULL);
            break;
        }
    case WM_CHANGECBCHAIN:
        {
            AfxBeginThread(FileArrival, NULL);
            break;
        }       
    }
    return CDialog::WindowProc(message, wParam, lParam);
}

UINT FileArrival(LPVOID param)
{
    TCHAR lpszFileName[MAX_PATH];
    char *szTime;
    time_t thistime;
        OpenClipboard(0);
        HGLOBAL hGlobal = (HGLOBAL)GetClipboardData(CF_HDROP);
        if (hGlobal)
        {
            HDROP hDrop = (HDROP)GlobalLock(hGlobal);
            if (hDrop)
            {   
                time(&thistime);
                szTime = ctime(&thistime);
                DragQueryFile(hDrop, 0, lpszFileName, MAX_PATH);
                WriteLog((char*)lpszFileName,1);
                GlobalUnlock(hGlobal);
            }
        CloseClipboard();
    }
    return 0;
}

This code works fine when we copy 1 file, but when we copy several files, it shows only the first file. Is there a way to find out all the file names copied to the clipboard.

+4
source share
1 answer

You use this to find the number of deleted files:

UINT fileCount = DragQueryFile(hDrop, 0xFFFFFFFF, nullptr, 0);

Using this information, you can select an array of strings and save each file name in an array string:

TCHAR** filenames;
// other code . . .
filenames = malloc(fileCount * sizeof(TCHAR*));
// other code . . .
for (UINT i = 0; i < fileCount; ++i) {
    UINT filenameLength = DragQueryFile(hDrop, i, nullptr, 0);
    filenames[i] = malloc(filenameLength);
    DragQueryFile(hDrop, i, filenames[i], filenameLength);
}

I understood all this by reading the documentation .

EDIT: ++ ( free), :

std::vector<std::basic_string<TCHAR> > filenames(fileCount);
// other code . . .
for (UINT i = 0; i < fileCount; ++i) {
    UINT filenameLength = DragQueryFile(hDrop, i, nullptr, 0);
    filenames[i].reserve(filenameLength);
    DragQueryFile(hDrop, i, &(filenames[i][0]), filenameLength);
    // Uncomment the below line and comment the above line if you can use C++17 features
    // DragQueryFile(hDrop, i, filenames[i].data(), filenameLength);
}
+7

Source: https://habr.com/ru/post/1675603/


All Articles