简体   繁体   English

在winapi的CALLBACK函数上返回FALSE时发生意外行为(跳过循环?)

[英]Unexpected behavior when returning FALSE on winapi CALLBACK function (loop gets skipped?)

I have the following function. 我有以下功能。 If the return on the bottom of the function is TRUE works as expected. 如果函数底部的返回值为TRUE预期方式工作。

But if I change it to FALSE ( to know if regex_match yield a result) it seems to completely skip the for loop and returns FALSE directly. 但是,如果我将其更改为FALSE (以了解regex_match是否产生结果),它似乎会完全跳过for循环并直接返回FALSE I'm very un-familiar with winapi so i might been using return value unappropriate. 我对winapi非常不熟悉,因此我可能使用了不合适的返回值。

I tried both g++ and msvc w/o optimizer, but got the same behavior. 我尝试了g ++和msvc w / o Optimizer,但是得到了相同的行为。

BOOL CALLBACK enumWindowsProc(HWND hwnd, LPARAM lParam) {

    static const std::wregex rgx(L"(.+) - (?!\\{)(.+)");
    const auto &paramRe = *reinterpret_cast<EnumWindowsProcParam*>(lParam);

    DWORD winId;
    GetWindowThreadProcessId(hwnd, &winId);

    for (DWORD pid : (paramRe.pids)) {
        if (winId == pid) {
            std::wstring title(GetWindowTextLength(hwnd) + 1, L'\0');
            GetWindowTextW(hwnd, &title[0], title.size()); //note: >=C++11 

            std::regex_match(title, rgx);
            std::wsmatch matches;

            if (std::regex_search(title, matches, rgx)) {
                paramRe.song = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(matches[1]);
                paramRe.artist = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(matches[2]);
                return TRUE;
            }
        }
    }
    return TRUE;  // <--- HERE
}

Idk, if rest of the code matters, but as said if default return value is true the code works as intended I just don't know if match was found (I know I could check if value of strings change, or pass that info to the lparam struct I use, but that still raises the question why is that happening.) Idk,如果其余代码很重要,但是如前所述,如果默认返回值为true,则代码按预期工作,我只是不知道是否找到匹配项(我知道我可以检查字符串的值是否更改,或将该信息传递给我使用的lparam结构,但这仍然引发了一个问题,为什么会发生这种情况。)

First off, CALLBACK is just the function calling convention and has nothing to do with when the enumeration stops. 首先, CALLBACK只是函数调用约定,与枚举停止时无关。

MSDN clearly says: MSDN明确指出:

EnumWindows continues until the last top-level window is enumerated or the callback function returns FALSE. EnumWindows继续,直到枚举最后一个顶级窗口或回调函数返回FALSE。

If you need to record some specific information regarding finding a match then you should store that in the struct you pass as the LPARAM parameter. 如果您需要记录一些有关查找匹配项的特定信息,则应将其作为LPARAM参数存储在传递的结构中。

If you only care about the first window that matches then you can return FALSE once that window is found, this aborts the enumeration without having to inspect the remaining windows. 如果仅关心匹配的第一个窗口,则一旦找到该窗口,便可以返回FALSE ,这将中止枚举,而无需检查其余窗口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM