Home > Software design >  Thread is terminated for no apparent reason
Thread is terminated for no apparent reason

Time:09-06

So I am currently making a system to list all visible windows and then choose a random one. The code exists and is working.. in 32-bit. The problem is that it won't work when compiling for 64-bit. It does not even hit my breaking point before terminating the thread. I have also tried using a try block with the same result. The thread exit code is 0. NOTE: The code is messy due to it being filled with debugging and testing stuff.

Here is my code:

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    wchar_t wnd_title[2048]; // Will be replaced
    SendMessage(hwnd, WM_GETTEXT, sizeof(wnd_title), (LPARAM)wnd_title);

    if (!hwnd || !IsWindowVisible(hwnd) || !SendMessage(hwnd, WM_GETTEXT, sizeof(wnd_title), (LPARAM)wnd_title)) {
        return TRUE;
    }
    
    std::vector<HWND>& Windows = *reinterpret_cast<std::vector<HWND>*>(lParam);
    Windows.push_back(hwnd);

    OutputDebugString(wnd_title);
    OutputDebugString(L"\n");

    return TRUE;
}

std::vector<HWND> GetOpenWindows() {
    std::vector<HWND> Windows;
    EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(&Windows));
    return Windows;
}

void GetRandomWindow() {
    stringstream ss;    // For Debug
    std::ostringstream stream;  //For Debug

    std::vector<HWND> Windows = GetOpenWindows();
    int ChosenWindow = Utils::RandIntRange(0, Windows.size());

    if (ChosenWindow < Windows.size()) {    // Breaking point here (HIT)
        TCHAR wnd_title[MAX_PATH];
        SendMessage(Windows[ChosenWindow], WM_GETTEXT, MAX_PATH, (LPARAM)wnd_title);    //Breaking point here (NOT HIT)
        OutputDebugString(L"\n");
        OutputDebugString(wnd_title);
        MessageBox(NULL, L"Hi", L"Test", MB_OK);
    }
}

CodePudding user response:

The thread was terminated because the wrong size was passed to the message. The thread hang issue was fixed by using SendMessageTimeout(...); instead of SendMessage(..);. This works because a window was not responding to any messages.

(Answer is for people who have the same issue)

Thanks to Igor Tandetnik and Peter for the help!

  • Related