mardi 29 juin 2021

Message queue for two cpp file with windows API

To send the message in the Queue from one source file and get the message in another source file.I read the docs from Microsoft and try to implement as below

test2.cpp - post the message main.c - get the Message

Testing1: If i execute the same code in single file that get executed and i receive the data

Testing : Same code is written in two separate file "if (msg.message == WM_YOUR_MESSAGE)" these statement does not get satisfied.

/* Unique IDs for Window messages to exchange between the worker and the GUI thread. */
#define WM_YOUR_MESSAGE   ( WM_USER + 3 )

 typedef struct
{
int SomeData1;
int SomeData2;
int SomeDataN;
} MessageData;

volatile DWORD ThreadID_GUI;

void __cdecl ThreadProc(void* aArg)
{
    MessageData* data;

   for (;; )
   {
      Sleep(500);

    /* Allocate memory for a new message data structure */
    data = (MessageData*)malloc(sizeof(*data));

    /* Initialize the message data structure with some information to transfer
       to the GUI thread. */
    data->SomeData1 = 1234;
    data->SomeData2 = 4567;
    data->SomeDataN = 7894;

   PostThreadMessage(ThreadID_GUI, WM_YOUR_MESSAGE, 0, (LPARAM)data);
}  }

main.c

#include<test.h>
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                 _In_opt_ HINSTANCE hPrevInstance,
                 _In_ LPWSTR    lpCmdLine,
                 _In_ int       nCmdShow)
   {
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

// TODO: Place code here.

ThreadID_GUI = GetCurrentThreadId();

/* Start some background thread */
_beginthread(ThreadProc, 0, 0);

// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_TESTMESSAGEQUEUE, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);

// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
    return FALSE;
}

HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TESTMESSAGEQUEUE));

MSG msg;

// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
        /* STEP 3: React on the message sent from the foreign thread */
        if (msg.message == WM_YOUR_MESSAGE)
        {
            MessageData* tmp = (MessageData*)msg.lParam;

                if (tmp->SomeData1 == 1234) {
                printf("someData\n");
            }
            /* Free the data structure associated to the message */
            free(tmp);
        }
        TranslateMessage(&msg);
        DispatchMessage(&msg);
}

return (int) msg.wParam;

}

Aucun commentaire:

Enregistrer un commentaire