如何使用win32 API实现将文件放入回收站

来源:互联网 发布:什么网络游戏支持mac 编辑:程序博客网 时间:2024/05/10 05:59

最近有同事提出了这个小需求,上班的时候一直没有心思考虑。周末的时候小小的实践了一把。现在贴出来,以后自己可以粘贴代码用。

这个功能很简单,我们常常会用到DeleteFile,但这个API是将文件完全删除而不会保存到回收站中。上网搜了下,大家都推荐使用SHFileOperation这个函数。先给大家看一下MSDN中的解释。如下:

Copies, moves, renames, or deletes a file system object.

Syntax

int SHFileOperation(          LPSHFILEOPSTRUCT lpFileOp);

Parameters

lpFileOp
[in] Pointer to an SHFILEOPSTRUCT structure that contains information this function needs to carry out the specified operation. This parameter must contain a valid value that is not NULL. You are responsibile for validating the value. If you do not validate it, you will experience unexpected results.

Return Value

Returns zero if successful, or nonzero otherwise.

Remarks

You should use fully-qualified path names with this function. Using it with relative path names is not thread safe.

With two exceptions, you cannot use SHFileOperation to move special folders from a local drive to a remote computer by specifying a network path. The exceptions are theMy Documents and My Pictures folders (CSIDL_PERSONAL and CSIDL_MYPICTURES, respectively).

When used to delete a file, SHFileOperation permanently deletes the file unless you set theFOF_ALLOWUNDO flag in the fFlags member of theSHFILEOPSTRUCT structure pointed to by lpFileOp. Setting that flag sends the file to the Recycle Bin. If you want to delete a file and guarantee that it is not placed in the Recycle Bin, use DeleteFile.

If a copy callback handler is exposed and registered, SHFileOperation calls it unless you set a flag such asFOF_NOCONFIRMATION in the fFlags member of the structure pointed to bylpFileOp. See ICopyHook::CopyCallback for details on implementing copy callback handlers.

File deletion is recursive unless you set the FOF_NORECURSION flag inlpFileOp.


MSDN写得很多,主要就是说这个函数功能很强大!函数的参数只有一个,再仔细跟一下参数类型:SHFILEOPSTRUCT。 咱们也先看看MSDN的注释,如下:

Contains information that the SHFileOperation function uses to perform file operations.

Syntax

typedef struct _SHFILEOPSTRUCT {    HWND hwnd;    UINT wFunc;    LPCTSTR pFrom;    LPCTSTR pTo;    FILEOP_FLAGS fFlags;    BOOL fAnyOperationsAborted;    LPVOID hNameMappings;    LPCTSTR lpszProgressTitle;} SHFILEOPSTRUCT, *LPSHFILEOPSTRUCT;

Members

hwnd
Window handle to the dialog box to display information about the status of the file operation.
wFunc
Value that indicates which operation to perform. This member can be one of the following values.
FO_COPY
Copy the files specified in the pFrom member to the location specified in thepTo member.
FO_DELETE
Delete the files specified in pFrom.
FO_MOVE
Move the files specified in pFrom to the location specified inpTo.
FO_RENAME
Rename the file specified in pFrom. You cannot use this flag to rename multiple files with a single function call. UseFO_MOVE instead.
pFrom
Address of a buffer to specify one or more source file names. These names must be fully qualified paths. Standard Microsoft MS-DOS wild cards, such as "*", are permitted in the file-name position. Although this member is declared as a null-terminated string, it is used as a buffer to hold multiple file names. Each file name must be terminated by a single NULL character. An additional NULL character must be appended to the end of the final name to indicate the end ofpFrom.
pTo
Address of a buffer to contain the name of the destination file or directory. This parameter must be set to NULL if it is not used. LikepFrom, the pTo member is also a double-null terminated string and is handled in much the same way. However,pTo must meet the following specifications.
  • Wildcard characters are not supported.
  • Copy and Move operations can specify destination directories that do not exist and the system will attempt to create them. The system normally displays a dialog box to ask the user if they want to create the new directory. To suppress this dialog box and have the directories created silently, set the FOF_NOCONFIRMMKDIR flag infFlags.
  • For Copy and Move operations, the buffer can contain multiple destination file names if thefFlags member specifiesFOF_MULTIDESTFILES.
  • Pack multiple names into the string in the same way as for pFrom.
  • Use only fully-qualified paths. Using relative paths will have unpredictable results.
fFlags
Flags that control the file operation. This member can take a combination of the following flags.
FOF_ALLOWUNDO
Preserve undo information, if possible. Operations can be undone only from the same process that performed the original operation. IfpFrom does not contain fully qualified path and file names, this flag is ignored.
FOF_CONFIRMMOUSE
Not used.
FOF_FILESONLY
Perform the operation on files only if a wildcard file name (*.*) is specified.
FOF_MULTIDESTFILES
The pTo member specifies multiple destination files (one for each source file) rather than one directory where all source files are to be deposited.
FOF_NOCONFIRMATION
Respond with "Yes to All" for any dialog box that is displayed.
FOF_NOCONFIRMMKDIR
Do not confirm the creation of a new directory if the operation requires one to be created.
FOF_NO_CONNECTED_ELEMENTS
Version 5.0. Do not move connected files as a group. Only move the specified files.
FOF_NOCOPYSECURITYATTRIBS
Version 4.71. Do not copy the security attributes of the file.
FOF_NOERRORUI
Do not display a user interface if an error occurs.
FOF_NORECURSION
Only operate in the local directory. Don't operate recursively into subdirectories.
FOF_NORECURSEREPARSE
Treat reparse points as objects, not containers. You must set _WIN32_WINNT to 5.01 or later to use this flag. SeeShell and Common Controls Versions for further discussion of versioning.
FOF_RENAMEONCOLLISION
Give the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists.
FOF_SILENT
Do not display a progress dialog box.
FOF_SIMPLEPROGRESS
Display a progress dialog box but do not show the file names.
FOF_WANTMAPPINGHANDLE
If FOF_RENAMEONCOLLISION is specified and any files were renamed, assign a name mapping object containing their old and new names to thehNameMappings member.
FOF_WANTNUKEWARNING
Version 5.0. Send a warning if a file is being destroyed during a delete operation rather than recycled. This flag partially overridesFOF_NOCONFIRMATION.
fAnyOperationsAborted
Value that receives TRUE if the user aborted any file operations before they were completed, or FALSE otherwise.
hNameMappings
A handle to a name mapping object containing the old and new names of the renamed files. This member is used only if thefFlags member includes theFOF_WANTMAPPINGHANDLE flag. See Remarks for more details.
lpszProgressTitle
Address of a string to use as the title of a progress dialog box. This member is used only iffFlags includes the FOF_SIMPLEPROGRESS flag.

Remarks

If the pFrom or pTo members are unqualified names, the current directories are taken from the global current drive and directory settings as managed by the GetCurrentDirectory and SetCurrentDirectory functions.

If pFrom is set to a file name, deleting the file withFO_DELETE will not move it to the Recycle Bin, even if theFOF_ALLOWUNDO flag is set. You must use a full path.

There are two versions of this structure, an ANSI version (SHFILEOPSTRUCTA) and a Unicode version (SHFILEOPSTRUCTW). The Unicode version is identical to the ANSI version, except that wide character strings (LPCWSTR) are used in place of ANSI character strings (LPCSTR). On Microsoft Windows 98 and earlier, only the ANSI version is supported. On Microsoft Windows NT 4.0 and later, both the ANSI and Unicode versions of this structure are supported. SHFILEOPSTRUCTW and SHFILEOPTSTRUCTA should never be used directly; the appropriate structure is redefined as SHFILEOPSTRUCT by the precompiler depending on whether the application is compiled for ANSI or Unicode. SHNAMEMAPPING has similar ANSI and Unicode versions. For ANSI applications,hNameMappings points to an int followed by an array of ANSI SHNAMEMAPPING structures. For Unicode applications,hNameMappings points to an int followed by an array of Unicode SHNAMEMAPPING structures. However, on Windows NT 4.0 and later, SHFileOperation always returns a handle to a Unicode set ofSHNAMEMAPPING structures. If you want applications to be functional with all versions of Windows, the application must employ conditional code to deal with name mappings. For example:

x = SHFileOperation(&shop);if (fWin9x) HandleAnsiNameMappings(shop.hNameMappings);else HandleUnicodeNameMappings(shop.hNameMappings);

Treat hNameMappings as a pointer to a structure whose members are anUINT value followed by a pointer to an array of SHNAMEMAPPING structures, for example:

struct HANDLETOMAPPINGS {    UINT              uNumberOfMappings;  // number of mappings in array    LPSHNAMEMAPPING   lpSHNameMapping;    // pointer to array of mappings};
The UINT value is set to the number of SHNAMEMAPPING structures in the array. EachSHNAMEMAPPING structure contains the old and new path for one of the renamed files.


好吧,准备工作已经结束。不好意思,我废话太多。。。。

先看我的代码实现吧~




LPCTSTR lpszFile = _T("test.txt");


TCHAR szPath[MAX_PATH + 1] = {0};
TCHAR szFilePath[MAX_PATH + 1] = {0};
if(GetModuleFileName(NULL,szPath,MAX_PATH))
{
if(PathRemoveFileSpec(szPath))
{
int nLen = _tcslen(szPath);
if(szPath[nLen - 1] == _T('\\'))
{
szPath[nLen - 1] = 0;
nLen -= 1;
}
_sntprintf(szFilePath,MAX_PATH,_T("%s\\%s"),szPath,lpszFile);

if(PathFileExists(lpszFile))
{
SHFILEOPSTRUCT sctFileOp = {0};

sctFileOp.wFunc = FO_DELETE;
sctFileOp.pTo = NULL;

sctFileOp.pFrom = szFilePath;
sctFileOp.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
if(0 == SHFileOperation(&sctFileOp))
{
MessageBox(NULL,_T("Delete File OK!"),_T("Tips"),MB_OK);
}
}
}
}


大家只要注意我标红的地方就OK了,其它地方不多解释啊~

经测试,本段代码有效可用~


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 魅族手机屏幕锁密码忘了怎么办 手机没设置魅族账号密码忘了怎么办 魅族手机格式化密码忘了怎么办 魅族手机忘记密码了怎么解锁怎么办 手机设置的应用加密忘记密码怎么办 手机上设置应用加密忘记密码怎么办 魅蓝flyme密码忘了怎么办图片 魅族手机经常自动账号锁屏怎么办 魅族锁定后又不知道密码怎么办 魅族手机锁屏锁定了怎么办 魅族手机已锁定怎么办密码忘了 京东抢到了小米8不发货怎么办 第一次网上预约没有就诊卡号怎么办 京东定金交了未发货怎么办 买了没有预售许可证的房子怎么办 买了没有预售证的房子怎么办 苹果手机发烫容易变3g网怎么办 魅族手机有指纹和密码怎么办刷机 魅族手机指纹解锁密码忘了怎么办 魅蓝5s运存占用太多怎么办 魅蓝e2手机照片被删了怎么办 魅蓝e2不小心删除了照片怎么办 魅蓝3s返回键失灵怎么办 糖猫电话手表屏碎了怎么办 魅蓝手机没下安装包强制更新怎么办 老婆赌博输了30多万现在怎么办啊 红米nt2手机通话声音小怎么办? 微信退出后重新登录忘记密码怎么办 微退出后再登录忘记密码了怎么办 忘记微信密码又退出微信怎么办 无线网自家密码忘了也连不上怎么办 无线网密码忘了连接不上怎么办 魅蓝手机插口半夜坏了怎么办 魅族手机换屏后出现跳屏怎么办 小米手机微信小程序转发不出怎么办 苹果手机ad码和密码忘了怎么办 魅族手机摔掉无法开机怎么办 魅族音量+电源键直接开机了怎么办 魅蓝2数字锁机了怎么办 苹果5s蓝屏开不了机怎么办 红米pro更新开发版发热卡怎么办