Node.js 和 C++ 结合 Win API 实现 Ctrl 键按下时获取选中文件类型
要实现这个功能,需要使用以下步骤:
-
使用 Node.js 的 child_process 模块调用 C++ 程序,让 C++ 程序监听 Win API 的消息。
-
在 C++ 程序中,使用 Windows API 的 SetWindowsHookEx 函数设置一个钩子函数,来监听键盘事件。
-
当用户按下 Ctrl 键时,钩子函数会被触发,可以使用 Windows API 的 GetCursorPos 函数获取鼠标位置。
-
使用 Windows API 的 WindowFromPoint 函数获取鼠标所在的窗口句柄,然后使用 Windows API 的 SendMessage 函数发送 WM_GETTEXT 消息,获取窗口中选中的文件路径。
-
使用 Node.js 的 child_process 模块将获取到的文件路径传递给 C++ 程序。
-
在 C++ 程序中,使用 Windows API 的 PathFindExtension 函数获取文件的扩展名,并根据扩展名判断文件类型。
-
将文件类型信息传递给 Node.js 程序,使用 console.log 函数打印出来。
下面是一个简单的示例代码:
Node.js 代码:
const { spawn } = require('child_process');
const cplusplus = spawn('./a.exe');
cplusplus.stdout.on('data', (data) => {
console.log(`C++ output: ${data}`);
});
cplusplus.stderr.on('data', (data) => {
console.error(`C++ error: ${data}`);
});
const stdin = process.openStdin();
stdin.addListener('data', (data) => {
cplusplus.stdin.write(data);
});
C++ 代码:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
HHOOK hHook = NULL;
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HC_ACTION && wParam == WM_KEYDOWN)
{
KBDLLHOOKSTRUCT* pKeyboardHook = (KBDLLHOOKSTRUCT*)lParam;
if (pKeyboardHook->vkCode == VK_CONTROL)
{
POINT pt;
if (GetCursorPos(&pt))
{
HWND hwnd = WindowFromPoint(pt);
if (hwnd != NULL)
{
int length = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0);
if (length > 0)
{
char* buffer = new char[length + 1];
SendMessage(hwnd, WM_GETTEXT, length + 1, (LPARAM)buffer);
printf('Selected file: %s\n', buffer);
string filepath(buffer);
ofstream output('output.txt');
output << filepath;
output.close();
delete[] buffer;
}
}
}
}
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
int main(int argc, char* argv[])
{
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, GetModuleHandle(NULL), 0);
if (hHook == NULL)
{
printf('Failed to set hook.\n');
return -1;
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hHook);
return 0;
}
在 C++ 代码中,当用户按下 Ctrl 键时,钩子函数会被触发,获取鼠标位置,并使用 SendMessage 函数获取窗口中选中的文件路径。然后将文件路径写入到 output.txt 文件中。
最后,Node.js 程序可以读取 output.txt 文件中的文件路径,并传递给 C++ 程序进行文件类型判断。
原文地址: https://www.cveoy.top/t/topic/oBj8 著作权归作者所有。请勿转载和采集!