c ++ - map - 获取此值的关键字

时间:2013-02-07 09:31:55

标签: c++ winapi map

我有一个std :: windows的地图,例如:

class MyWindow
{
public:
    MyWindow()
    {
        CreateWindow(...);
    }
    ... // rest of code
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        // code
    }
}

std::map<string, MyWindow> windows;

在WndProc函数中我想知道函数中现在有哪个窗口,如何获取该窗口的键。

3 个答案:

答案 0 :(得分:1)

如果MyWindow包含窗口句柄(HWND),那么您可以使用例如std::find_if找到实例。

类似的东西:

HWND hWnd;  // The window handle to look for

auto windowIterator = std::find_if(std::begin(windows), std::end(windows),
    [hWnd](const std::map<std::string, MyWindow>::value_type& p) -> bool {
        return (p.first.getNativeWindowHandle() == hWnd);
    });
if (windowIterator != std::end(windows))
{
    // `windowIterator` now "points" to the window
}

答案 1 :(得分:0)

对于给定的this,您可以使用SetWindowLongPtr存储指向对象的指针(HWND,如果您正在为类方法创建窗口)。使用GWLP_USERDATA作为nIndex参数。

这样,你根本不需要地图:当你有一个窗口句柄时,GetWindowLongPtr足以获得一个对象。

答案 2 :(得分:0)

您可以对地图进行强力搜索:

auto it = std::find_if(windows.begin(), windows.end(),
                       [this](std::pair<std::string const, MyWindow> const & p) -> bool
                       { return p.second == *this; } );

if (it == windows.end()) { /* not found */ }
else                     { /* window key is it->first */ }

如果对象是唯一的,您也可以在比较中说&p.second == this