How to use SHFileOperation

SHFileOperation is a Windows API function used for performing file operations such as copying, moving, renaming, and deleting. Here is the basic usage of the SHFileOperation function:

  1. Include header files and link libraries:
#include <Windows.h>
#pragma comment(lib, "shell32.lib")
  1. Create a SHFILEOPSTRUCT structure and configure its parameters.
SHFILEOPSTRUCT fileOp;
ZeroMemory(&fileOp, sizeof(fileOp));
fileOp.hwnd = NULL;  // 窗口句柄,可以为空
fileOp.wFunc = FO_COPY;  // 指定操作类型,例如复制、移动、删除等
fileOp.pFrom = sourceFilePath;  // 源文件路径,可以是多个文件或文件夹,用空字符分隔
fileOp.pTo = destinationFilePath;  // 目标文件路径,可以是目录或文件
fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;  // 设置选项,例如允许撤销、不显示确认对话框等
  1. Execute file operations using the SHFileOperation function.
int result = SHFileOperation(&fileOp);
if (result == 0) {
    // 操作成功
} else {
    // 操作失败,可以通过返回值和GetLastError函数获取错误信息
    DWORD error = GetLastError();
}

Please take note:

  1. Before using the SHFileOperation function, make sure that the operating system has been initialized.
  2. After using the SHFileOperation function, it is necessary to check the return value to determine if the operation was successful.
  3. Multiple options can be utilized when setting fileOp.fFlags by connecting them with the logical OR operator (|).
  4. When setting fileOp.pFrom and fileOp.pTo, it is necessary to use double null characters as separators for multiple files or folders.

The above is the basic usage of the SHFileOperation function. You can customize the parameters and error handling based on specific needs.

bannerAds