如何通过 win32 API 函数复制文件并在我的桌面中通过 (Ctrl+v) 粘贴

Jac*_*ack 2 winapi

我想通过 win32 API 函数复制一个文件,并通过 (Ctrl+c) 在我的其他 Windows 文件夹的桌面上“粘贴”它。

我知道 CopyFileEx 并用它复制文件,但此功能复制和粘贴。我只想在我的 main() 程序中复制文件(通过 win32 API 函数)并将其“粘贴”到桌面或 Windows 的其他文件夹中。

我不想使用 SHFileOperation 函数。

小智 6

这是一个最小的工作示例(控制台应用程序)。它针对 unicode 和非 unicode 环境进行编译。由于这是最小的,所以没有任何类型的错误处理(用法见下文)。

#include <Windows.h>
#include <Shlobj.h> // DROPFILES
#include <tchar.h>  // e.g. _tcslen

int _tmain(int argc, TCHAR* argv[])
{
    // calculate *bytes* needed for memory allocation
    int clpSize = sizeof(DROPFILES);
    for (int i = 1; i < argc; i++)
        clpSize += sizeof(TCHAR) * (_tcslen(argv[i]) + 1); // + 1 => '\0'
    clpSize += sizeof(TCHAR); // two \0 needed at the end

    // allocate the zero initialized memory
    HDROP hdrop   = (HDROP)GlobalAlloc(GHND, clpSize);
    DROPFILES* df = (DROPFILES*)GlobalLock(hdrop);
    df->pFiles    = sizeof(DROPFILES); // string offset
#ifdef _UNICODE
    df->fWide     = TRUE; // unicode file names
#endif // _UNICODE

    // copy the command line args to the allocated memory
    TCHAR* dstStart = (TCHAR*)&df[1];
    for (int i = 1; i < argc; i++)
    {
        _tcscpy(dstStart, argv[i]);
        dstStart = &dstStart[_tcslen(argv[i]) + 1]; // + 1 => get beyond '\0'
    }
    GlobalUnlock(hdrop);

    // prepare the clipboard
    OpenClipboard(NULL);
    EmptyClipboard();
    SetClipboardData(CF_HDROP, hdrop);
    CloseClipboard();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

用法:

fclip.exe "C:\full\path\to\file.dat" "C:\more\files.dat"
Run Code Online (Sandbox Code Playgroud)

就是这样!请随意按ctrl + v粘贴文件。


Rem*_*eau 5

如果您希望在粘贴剪贴板内容时将实际文件复制到目标文件夹,则需要使用以下CF_HDROP格式将路径字符串放到剪贴板上,例如:

// error handling omitted for brevity...

LPWSTR path = ...;
int size = sizeof(DROPFILES)+((lstrlenW(path)+2)*sizeof(WCHAR));
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, size);
DROPFILES *df = (DROPFILES*) GlobalLock(hGlobal);
ZeroMemory(df, size);
df->pFiles = sizeof(DROPFILES);
df->fWide = TRUE;
LPWSTR ptr = (LPWSTR) (df + 1);
lstrcpyW(ptr, path);
GlobalUnlock(hGlobal);
SetClipboardData(CF_HDROP, hGlobal);
Run Code Online (Sandbox Code Playgroud)

更新:或者,请参阅“The Old New Thing”博客上的以下文章:

将文件复制到剪贴板,以便您可以将其粘贴到资源管理器或电子邮件或其他任何内容中

它使用GetUIObjectOfFile()OleSetClipboard()代替CF_HDROP。但最终效果是相似的 - 放置在剪贴板上的对象代表目标文件,资源管理器在粘贴操作期间识别该对象,因此它将文件复制到正在粘贴的文件夹中。