如何在Node.js插件中泵送窗口消息? [英] How do I pump window messages in a nodejs addon?
问题描述
在Windows nodejs插件中,我创建了一个用于接收消息的窗口.
In a Windows nodejs addon, I've created a window for the purpose of receiving messages.
Handle<Value> MakeMessageWindow(const Arguments &args) { // exposed to JS
...
CreateWindow(L"ClassName", NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, 0);
...
}
我有一个wndproc函数.
I have a wndproc function.
Local<Function> wndProc;
LRESULT APIENTRY WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
// pack up the arguments into Local<Value> argv
wndProc->Call(Context::GetCurrent()->Global(), 3, argv);
}
现在我需要发送消息.通常,您会做类似的事情
Now I need to pump messages. Normally, you'd do something like
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
...但是由于它只会阻止v8事件循环,因此不起作用.
...but that won't work since it would just block the v8 event loop.
如何以不会阻塞v8的方式泵送Windows消息,并允许我的窗口接收消息时调用JS函数?
How do I pump Windows messages in a manner that won't block v8 and allows me to invoke a JS function when my window receives messages?
我假设libuv将起作用,但是我不确定如何从在单独线程上运行的C安全地调用JS函数,尤其是因为
I presume libuv will play a role, but I'm unsure exactly how to safely invoke a JS function from C running on a separate thread, especially since uv_async_send
is not guaranteed to invoke a callback every time you call it, and I need to ensure that my JS callback is called every time a window message is received.
推荐答案
我的错误是试图在V8线程上创建窗口.相反,应该使用 uv_thread_create
调用一个函数,该函数在新线程上创建窗口 ,然后继续执行其自己的消息泵循环.
My mistake was trying to create the window on the V8 thread. Instead, uv_thread_create
should be used to call a function that creates the window on a new thread and then proceeds to do its own message pump loop.
然后,wndproc函数需要以线程安全的方式将接收到的消息保存到队列中,然后使用 uv_async_send
通知V8线程消息已到达.
The wndproc function then needs to save received messages into a queue in a thread-safe manner and then use uv_async_send
to notify the V8 thread that messages have arrived.
消息入队后,将调用V8线程上的一个函数(该函数已传递给 uv_async_init
).该功能(线程安全)将每个待处理的消息从队列中弹出,并调用JS回调.
A function on the V8 thread (which was passed to uv_async_init
) is then invoked after messages are enqueued. The function (thread-safely) pops each pending message off the queue and invokes the JS callback.
这篇关于如何在Node.js插件中泵送窗口消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!