Windows下打开指定目录并定位到具体文件

打印 上一主题 下一主题

主题 876|帖子 876|积分 2628

一.在Windows上,网上流传的几种方法可以打开目录并定位到指定文件:

1.使用系统调用:


  • 使用system()函数执行操作系统的命令行命令。
  • 在命令行命令中,使用explorer /select, 文件路径来打开目录并选中指定文件。例如:
  1. #include <cstdlib>
  2. int main() {
  3.     std::string filePath = "C:\\路径\\到\\目标\\文件.txt";
  4.     std::string command = "explorer /select," + filePath;
  5.     system(command.c_str());
  6.     return 0;
  7. }
复制代码
2.使用ShellExecute函数:


  • 使用Windows API的ShellExecute()函数来打开目录并选中指定文件。
  • 使用ShellExecute(NULL, "open", "explorer.exe", "/select, 文件路径", NULL, SW_SHOW);来打开资源管理器并选中指定文件。例如:
    1. #include <windows.h>
    2. int main() {
    3.     const char* filePath = "C:\\路径\\到\\目标\\文件.txt";
    4.     ShellExecute(NULL, "open", "explorer.exe", ("/select," + std::string(filePath)).c_str(), NULL, SW_SHOW);
    5.     return 0;
    6. }
    复制代码
上面两种方式都可以打开并且定位,但是会存在一些问题,使用系统调用会出现一闪而过的黑窗口,还需要实现后台cmd执行,隐藏窗口;ShellExecute这个函数倒是很好用,但是你懂的这是个做什么的函数,基本各大杀毒都会重点监测的东西,带着ShellCode的函数在静态编译下能运行起来都已经是奇迹....

在这种情况下,还有别的骚操作可以实现打开目录,定位指定文件。

二.调用Windows中shlobj_core.h的API函数

1.使用SHOpenFolderAndSelectItems函数:


  • 使用PathFileExistsW() 先判断文件存在不存在
  • 使用ILCreateFromPathW() 获取指定文件路径关联的 ITEMIDLIST 结构
  • 使用SHOpenFolderAndSelectItems() 打开一个 Windows 资源管理器窗口,其中选定了特定文件夹中的指定项目。
  • 遵循SHOpenFolderAndSelectItems()使用规范,Com接口的初始化以及释放
  1. #include <iostream>
  2. #include <Windows.h>
  3. #include <shlwapi.h>
  4. #include <shlobj_core.h>
  5. #pragma comment(lib, "Shlwapi.lib")
  6. /// <summary>
  7. /// 成功则打开文件所在目录并选中文件
  8. /// </summary>
  9. /// <param name="unicode_filename">需提供文件的绝对路径</param>
  10. /// <param name="is_edit">重命名编辑模式</param>
  11. /// <returns></returns>
  12. bool open_file_location(const WCHAR* unicode_filename, bool is_edit = false)
  13. {
  14.         if (!PathFileExistsW(unicode_filename))
  15.         {
  16.                 return false;
  17.         }
  18.         PIDLIST_ABSOLUTE pidl = ILCreateFromPathW(unicode_filename);
  19.         if (pidl == NULL)
  20.         {
  21.                 return false;
  22.         }
  23.         CoInitialize(NULL);
  24.         HRESULT hr = SHOpenFolderAndSelectItems(pidl, 0, 0, is_edit == true ? OFASI_EDIT : 0);
  25.         CoUninitialize();
  26.         ILFree(pidl);
  27.         return hr == S_OK;
  28. }
  29. int main()
  30. {
  31.         open_file_location(L"C:\\Users\\FengTeng\\Desktop\\1.txt");
  32.         return 0;
  33. }
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

涛声依旧在

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表