簡體   English   中英

如何在 Electron/NodeJS 中將 hookWindowMessage WM_COPYDATA 回調參數轉換為 JavaScript?

[英]How can the hookWindowMessage WM_COPYDATA callback parameters be converted to JavaScript in Electron/NodeJS?

我們的 C++ 應用程序發送 WM_COPYDATA 消息:

typedef struct tagNotificationStruct {
    char msg[255];
} NotificationStruct;

void __stdcall LogMessageWrite()
{
    const char* pszMessage = "Test 1 2 3";

    NotificationStruct notification;
    strcpy(notification.msg, pszMessage);

    COPYDATASTRUCT copyDataStruct;
    copyDataStruct.dwData = 73; // random identification number
    copyDataStruct.cbData = sizeof(NotificationStruct);
    copyDataStruct.lpData = &notification;

    string text = "my window title";
    wchar_t wtext[15];
    mbstowcs(wtext, text.c_str(), text.length());
    LPWSTR ptr = wtext;
    HWND hwDispatch = FindWindow(NULL, ptr);

    if (hwDispatch != NULL) {
        SendMessage(hwDispatch, WM_COPYDATA, NULL, (LPARAM)(LPVOID)& copyDataStruct);
    }
}

在我們的 Electron 應用程序中,我們在 JavaScript 中偵聽 WM_COPYDATA 消息:

browserWindow.hookWindowMessage(0x4A /* = WM_COPYDATA */, (wParam, lParam) => {
                console.log('wParam = ', wParam);
                console.log('lParam = ', lParam);
            });

我們收到消息,它給出了這個控制台 output:

wParam =  <Buffer@0x0000018C305F7160 00 00 00 00 00 00 00 00>
lParam =  <Buffer@0x0000018C305F6EC0 a0 f2 cf 42 8a 00 00 00>

我們如何在 JavaScript 中解釋這一點,以便我們可以讀取從 C++ 程序發送的字符串?

const ref = require('ref-napi');

browserWindow.hookWindowMessage(0x4A /* = WM_COPYDATA */, (wParam, lParam) => {

    // lParam is already a 64 bits pointer stored in an 8 bytes Buffer
    // ---------------------------------------------------------------

    // using that pointer, dereference the COPYDATASTRUCT
    // which is 20 bytes in a 64 bits process
    // --------------------------------------------------
    const CopyDataStruct = ref.readPointer(lParam, 0, 20);

    // Read the dwData member at offset 0,
    // which is 8 bytes in a 64 bits process
    // -------------------------------------
    const dwData = CopyDataStruct.readUInt64LE(0);

    // Do not touch if we don't know...
    // --------------------------------
    if ( dwData === 73 ) {
    
        // Read the lpData member
        // ----------------------
        const lpData = CopyDataStruct.readUInt64LE(12);
    
        // Read the size
        // -------------
        const cbData = CopyDataStruct.readUInt32LE(8);
    
        // Reuse the lParam pointer
        // ------------------------
        lParam.writeUInt64LE(lpData, 0);
    
        // Dereference the NotificationStruct
        // ----------------------------------
        const NotStruct = ref.readPointer(lParam, 0, cbData);
        const Text = NotStruct.toString('ascii').split('\0')[0];
        console.log( "Text is: " + Text);
    }    
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM