Home > database >  How do I pass the main window's handle to a new thread using win32 API only?
How do I pass the main window's handle to a new thread using win32 API only?

Time:11-24

I have read that I need to have the HWND placed on the heap. Is that correct?

I need this to read values from user input.

Thank you in advance!

VOID MakeThread(HWND hWnd)
{

    HWND* h = new HWND(hWnd);
    HANDLE hThread = (HANDLE)_beginthreadex(nullptr, 0, WorkerThread, h, 0, nullptr);

    if (hThread != nullptr) {
        WaitForSingleObject(hThread, INFINITE);
        CloseHandle(hThread);
    }
    delete h;
}

unsigned int __stdcall WorkerThread(VOID* h)
{
char num[71] = { 0 };
GetDlgItemTextA((*(HWND*)h), 2001, num, 70);

//Get number from edit box 2001
//Do work with the above-mentioned number

    return 0;
}

CodePudding user response:

I have read that I need to have the HWND placed on the heap. Is that correct?

Not really. Assuming that the HWND remains valid for the duration of the created thread (if it is the application's main window, then that is a reasonable assumption), and that the MakeThread function will not return until that thread is finished (as is the case in your code), then you can just give the address of its HWND hWnd argument as the arglist parameter in the call to _beginthreadex.

You don't have to create a copy of that window handle on the heap. Here's a simplified version of your MakeThread function:

VOID MakeThread(HWND hWnd)
{
    stringstream stream;
    stream << &hWnd << "\n" << hWnd;
    std::string s = stream.str();
    MessageBoxA(hWnd, s.c_str(), "Caller: hWnd?", 0);
    HANDLE hThread = (HANDLE)_beginthreadex(nullptr, 0, WorkerThread, &hWnd, 0, nullptr);
    if (hThread != nullptr) {
        WaitForSingleObject(hThread, INFINITE);
        CloseHandle(hThread);
    }
}

However, if your MakeThread function were to return without waiting for the created thread to complete, then that passed address would become invalid (at some point). But, in that scenario, you would have to make other changes to your code, so that you could keep track of the created thread handle.

CodePudding user response:

As soon as you use new HWND(hWnd), your object will be allocated on the heap by default, not stack. Thus, you can share it across without a risk the object to be lost due the stack unwinding.

Another point is you start the thread and then wait for the completion. As a side-effect, you could use even a stack-allocated data to pass to the thread because the stack is here until the thread exit (exactly, WaitForSingleObject line).

And handling user input is not related to heap/stack allocation in general. Could you re-phrase your question in that part or create another question on that mean?

  • Related