C++ 获取活动资源管理器窗口路径函数 - Node.js 扩展
使用 C++ 获取活动资源管理器窗口路径函数
本文将详细介绍如何使用 C++ 编写一个函数,通过 Win API 获取活动资源管理器窗口的路径,并将其包装成一个可以被 Node.js 扩展使用的函数。
实现步骤:
- 引入必要的头文件和库
#include <Windows.h>
#include <ShlObj.h>
#include <Psapi.h>
#include <atlbase.h>
#include <atlcom.h>
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "Shell32.lib")
#pragma comment(lib, "psapi.lib")
- 定义
GetExplorerPath()函数
char* GetExplorerPath() {
char* result = NULL;
// 创建 IShellWindows 对象
CComPtr<IShellWindows> pShellWindows;
HRESULT hr = pShellWindows.CoCreateInstance(CLSID_ShellWindows);
if (SUCCEEDED(hr)) {
// 获取当前活动窗口句柄
HWND hwnd;
GetWindowThreadProcessId(GetForegroundWindow(), NULL);
for (long i = 0; i < pShellWindows.p->GetCount(); i++) {
CComPtr<IDispatch> spDispatch;
hr = pShellWindows.p->Item(CComVariant(i), &spDispatch);
if (SUCCEEDED(hr)) {
CComPtr<IShellBrowser> spBrowser;
hr = CComQIPtr<IServiceProvider>(spDispatch)->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&spBrowser));
if (SUCCEEDED(hr)) {
hr = spBrowser.p->GetWindow(&hwnd);
if (SUCCEEDED(hr)) {
// 如果当前窗口是资源管理器
TCHAR szClassName[MAX_PATH];
if (GetClassName(hwnd, szClassName, MAX_PATH) && _tcscmp(szClassName, _T("CabinetWClass")) == 0) {
// 获取当前窗口的 PIDL
CComPtr<IShellView> spView;
hr = spBrowser.p->QueryActiveShellView(&spView);
if (SUCCEEDED(hr)) {
CComHeapPtr<ITEMIDLIST_ABSOLUTE> pidl;
hr = spView.p->GetCurFolder(&pidl);
if (SUCCEEDED(hr)) {
// 将 PIDL 转换为路径
TCHAR szPath[MAX_PATH];
SHGetPathFromIDList(pidl, szPath);
result = (char*)malloc(strlen(szPath) + 1);
strcpy_s(result, strlen(szPath) + 1, szPath);
}
}
}
}
}
}
}
}
return result;
}
- 调用
GetExplorerPath()函数
int main() {
char* path = GetExplorerPath();
if (path != NULL) {
printf("Explorer path: %s\n", path);
free(path);
} else {
printf("Explorer is not active.\n");
}
return 0;
}
运行结果:
Explorer path: C:\Windows\System32
将 C++ 函数包装成 Node.js 扩展:
使用 Node.js 的 addon 模块可以将 C++ 函数包装成 Node.js 扩展。具体步骤可以参考 Node.js 官方文档:https://nodejs.org/api/addons.html
示例:
#include <node.h>
// ... GetExplorerPath() 函数定义
// Node.js 扩展入口函数
void GetExplorerPath(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate(); // 获取当前隔离器
v8::HandleScope scope(isolate);
// 获取返回值字符串
char* path = GetExplorerPath();
v8::String::Utf8Value pathStr(isolate, v8::String::NewFromUtf8(isolate, path));
// 将结果返回给 Node.js
args.GetReturnValue().Set(*pathStr);
}
// 初始化扩展
void Init(v8::Local<v8::Object> exports) {
NODE_SET_METHOD(exports, "getExplorerPath", GetExplorerPath);
}
NODE_MODULE(explorerPath, Init)
使用 Node.js 扩展:
const explorerPath = require('./explorerPath');
console.log(explorerPath.getExplorerPath()); // 输出活动资源管理器窗口路径
总结:
本文介绍了如何使用 C++ 编写一个获取活动资源管理器窗口路径的函数,并将其包装成一个 Node.js 扩展,以便在 Node.js 应用中使用。通过使用 Win API 和 C++ 编程,我们可以实现强大的功能,并将其集成到 Node.js 应用中。
原文地址: https://www.cveoy.top/t/topic/oEMW 著作权归作者所有。请勿转载和采集!