这是我要使用此WinAPI函数执行的操作:

EnumWindows(
    _In_ WNDENUMPROC lpEnumFunc,
    _In_ LPARAM      lParam
);


从此类FeedWindowsHandlesListWinFinder函数(在此简化)中调用它。

class WinFinder
{
    WinFinder();
    ~WinFinder();

    std::vector<HWND> winHandles;
    void FeedWindowsHandlesList();
};


FeedWinDowsHandlesList函数调用EnumWindows,依次为找到的每个句柄触发一个回调。在那里,HWND被添加到调用winHandles实例的WinFinder成员中。我面临的挑战是访问调用WinFinder实例的成员。我尝试了两种方法,它们都以相同的方式失败。



方法1 :(受此SO post启发)

调用函数:

void WinFinder::FeedWindowsHandlesList() {
    LPARAM param = reinterpret_cast<LPARAM>(this);
    EnumWindows(EnumWindowsProc, param);
}


回调(简体):

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
    WinFinder thisWF = *(reinterpret_cast<WinFinder*>(lParam));
    thisWF.winHandles.push_back(hWnd);
    return TRUE;
}


push_back级别的断点让我看到发生了添加,并且vector的大小变为1。但是下次我进入回调时,vector为空。 EnumWindows完成后,vector完全为空。



我也这样尝试过

方法2:

调用函数:

void WinFinder::FeedWindowsHandlesList() {
    WinFinder * wf =this;
    EnumWindows(EnumWindowsProc,(LPARAM)wf);
}


打回来:

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
    WinFinder thisWF= *((WinFinder*)lParam);
    thisWF.winHandles.push_back(hWnd);
 return TRUE;
}


因此,您认为我如何做才能访问调用vectorWinFinder类的EnumWindows成员,而又不会丢失任何内容?

最佳答案

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
    // WinFinder thisWF = *(reinterpret_cast<WinFinder*>(lParam));
    // in the above line you're creating a copy of the object pointed to by lParam
    // what you want instead is just a pointer of type WinFinder to simplify access:
    WinFinder *thisWF = reinterpret_cast<WinFinder*>(lParam);
    // thisWF.winHandles.push_back(hWnd);
    // since thisWF is a pointer you have to use -> to access the members:
    thisWF->winHandles.push_back(hWnd);
    return TRUE;
}


计划B:使用参考(由@SoronelHaetir建议):

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
    WinFinder &thisWF = *reinterpret_cast<WinFinder*>(lParam);
    thisWF.winHandles.push_back(hWnd);
    return TRUE;
}


最小示例:

#include <iostream>
#include <vector>
#include <Windows.h>

struct WinFinder
{
    std::vector<HWND> winHandles;
    void FeedWindowsHandlesList();
};

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
    WinFinder *thisWF = reinterpret_cast<WinFinder*>(lParam);
    thisWF->winHandles.push_back(hWnd);
    return TRUE;
}

void WinFinder::FeedWindowsHandlesList()
{
    LPARAM param = reinterpret_cast<LPARAM>(this);
    EnumWindows(EnumWindowsProc, param);
}

int main()
{
    WinFinder wf;
    wf.FeedWindowsHandlesList();

    for (auto const & w : wf.winHandles)
        std::cout << w << '\n';
}

关于c++ - 无法从回调中永久更改类的状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51572485/

10-11 22:47
查看更多