为了能到远方,脚下的每一步都不能少.|

高粱地里写BUG

园龄:3年4个月粉丝:4关注:3

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

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

1.使用系统调用:

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

2.使用ShellExecute函数:

  • 使用Windows API的ShellExecute()函数来打开目录并选中指定文件。
  • 使用ShellExecute(NULL, "open", "explorer.exe", "/select, 文件路径", NULL, SW_SHOW);来打开资源管理器并选中指定文件。例如:
    1
    2
    3
    4
    5
    6
    7
    #include <windows.h>
     
    int main() {
        const char* filePath = "C:\\路径\\到\\目标\\文件.txt";
        ShellExecute(NULL, "open", "explorer.exe", ("/select," + std::string(filePath)).c_str(), NULL, SW_SHOW);
        return 0;
    }

上面两种方式都可以打开并且定位,但是会存在一些问题,使用系统调用会出现一闪而过的黑窗口,还需要实现后台cmd执行,隐藏窗口;ShellExecute这个函数倒是很好用,但是你懂的这是个做什么的函数,基本各大杀毒都会重点监测的东西,带着ShellCode的函数在静态编译下能运行起来都已经是奇迹....

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

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

1.使用SHOpenFolderAndSelectItems函数:

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

 

posted @   高粱地里写BUG  阅读(958)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起