How do I pump window messages in a nodejs addon?
I needed to do this for Canon's EDSDK, which requires a message pump.
libuv's uv_idle_t
is a good candidate for this:
Despite the name, idle handles will get their callbacks called on every loop iteration, not when the loop is actually “idle”
Example:
#include <uv.h>
uv_idle_t* idle = new uv_idle_t();
uv_idle_init(uv_default_loop(), idle);
uv_idle_start(idle, idle_winmsg);
void idle_winmsg (uv_idle_t* idle) {
MSG msg;
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
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.
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.
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.