Node.js 获取剪贴板内容: C++ 模块示例
在 Node.js 中获取鼠标复制的内容需要使用系统级别的 API,因此需要编写 C++ 模块。以下是一个简单的示例代码,可以在 Windows 平台上获取鼠标复制的内容:
#include <node.h>
#include <Windows.h>
#include <string>
using namespace v8;
void GetClipboardText(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (!OpenClipboard(NULL)) {
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, 'Failed to open clipboard')));
return;
}
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
if (hData == NULL) {
CloseClipboard();
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, 'Failed to get clipboard data')));
return;
}
LPCWSTR pszText = static_cast<LPCWSTR>(GlobalLock(hData));
if (pszText == NULL) {
GlobalUnlock(hData);
CloseClipboard();
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, 'Failed to lock clipboard')));
return;
}
std::wstring text(pszText);
GlobalUnlock(hData);
CloseClipboard();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, reinterpret_cast<const char*>(text.c_str())));
}
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, 'getClipboardText', GetClipboardText);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
这个模块暴露了一个名为 getClipboardText 的函数,可以用以下方式在 Node.js 中调用:
const addon = require('./build/Release/addon.node');
console.log(addon.getClipboardText());
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ouxb 著作权归作者所有。请勿转载和采集!