gpt4 book ai didi

c++ - 如何获取拖入 Win32 应用程序的文件路径并将其删除?

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:37 26 4
gpt4 key购买 nike

我有一个程序,当他们将文件放入其中时,我希望它让路径显示“路径”的消息框,然后将其删除。谁能阐明如何做到这一点?

最佳答案

首先,您需要一个可以接受拖放文件的窗口。这是通过将窗口的 ExStyle 设置为 WS_EX_ACCEPTFILES 来实现的:

//Create a window.
hWnd = CreateWindowEx
WS_EX_ACCEPTFILES, // Extended possibilites for variation.
gsClassName, // Classname.
gsTitle, // Title caption text.
WS_OVERLAPPEDWINDOW, // Default window.
CW_USEDEFAULT, // X Position.
CW_USEDEFAULT, // Y position.
230, // Window starting width in pixils.
150, // Window starting height in pixils.
HWND_DESKTOP, // The window is a child-window to desktop.
(HMENU)NULL, // No menu.
hInstance, // Program Instance handler.
NULL // No Window Creation data.
);

其次,您需要在 WinProc() 回调中处理 WM_DROPFILES 消息。

if(uMessage == WM_DROPFILES)
{
HDROP hDropInfo = (HDROP)wParam;
char sItem[MAX_PATH];
for(int i = 0; DragQueryFile(hDropInfo, i, (LPSTR)sItem, sizeof(sItem)); i++)
{
//Is the item a file or a directory?
if(GetFileAttributes(sItem) &FILE_ATTRIBUTE_DIRECTORY)
{
//Delete all of the files in a directory before we can remove it.
DeleteDirectoryRecursive(sItem);
}
else {
SetFileAttributes(sItem, FILE_ATTRIBUTE_NORMAL); //Make file writable
//DeleteFile(sItem);
}

}
DragFinish(hDropInfo);
}

第三,您需要一个函数,可以从拖放到对话框中的任何目录中删除所有子目录和文件:

bool DeleteDirectoryRecursive(const char *sDir)
{
WIN32_FIND_DATA fdFile;
HANDLE hFind = NULL;

char sPath[2048];

//Specify a file mask. *.* = We want everything!
sprintf(sPath, "%s\\*.*", sDir);

if((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE)
{
printf("Path not found: [%s]\n", sDir);
return false;
}

do
{
//Find first file will always return "."
// and ".." as the first two directories.
if(strcmp(fdFile.cFileName, ".") != 0
&& strcmp(fdFile.cFileName, "..") != 0)
{
//Build up our file path using the passed in
// [sDir] and the file/foldername we just found:
sprintf(sPath, "%s\\%s", sDir, fdFile.cFileName);

//Is the entity a File or Folder?
if(fdFile.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
{
DeleteDirectoryRecursive(sPath); //Recursive call.
}
else{
printf("File: %s\n", sPath);
SetFileAttributes(sPath, FILE_ATTRIBUTE_NORMAL);
//DeleteFile(sPath);
}
}
}
while(FindNextFile(hFind, &fdFile)); //Find the next file.

FindClose(hFind); //Always, Always, clean things up!

SetFileAttributes(sDir, FILE_ATTRIBUTE_NORMAL);
//RemoveDirectory(sDir); //Delete the directory that was passed in.

return true;
}

最后,您需要非常小心此代码段 - 毕竟它会删除文件。

关于c++ - 如何获取拖入 Win32 应用程序的文件路径并将其删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2263586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com