我有一个使用EnumWindows的类。因为这需要一个回调,我把它包装成一个很好的小工具类,类似于:
Class Tools
{
public:
template<typename WinFunctor>
std::vector<HWND> FindWindow(WinFunctor Functor);
private:
BOOL EnumWindowMsgProc(HWND hWnd);
static BOOL CALLBACK FreeWndProc(HWND hWnd, LPARAM lParam)
{
Tools* pThis = (Tools*)lParam;
return pThis->EnumWindowMsgProc(hWnd);
}
std::vector<HWND> m_Windows;
/*Need to store WinFunctor Here*/
}
BOOL Tools::EnumWindowMsgProc(HWND hWnd)
{
if(/*Call WinFunctor Member here*/)
{
m_Windows.push_back(hWnd);
}
return TRUE;
}
template<typename WinFunctor>
std::vector<HWND> Tools::FindWindow(WinFunctor Functor)
{
m_Windows.clear();
EnumWindows(FreeWndProc, (LPARAM)this);
return m_Windows;
}
/*Windows Callbacks must be free (not a class member),
so I define a static method (free) and forward to my
member function(not free)*/
WinFunctor示例:
bool EnumByWindowName(HWND WinHandle,const std::wstring& WinName)
{
wchar_t Temp[1024]{L'\0'};
GetWindowText(WinHandle, Temp, 1024);
if (std::wstring(Temp).compare(WinName.c_str()) == 0)
return true;
return false;
}
所需界面的示例
Tools ToolInst;
auto Windows=ToolsInst.FindWindow(EnumByWindowName(std::placeholders::_1,"Notepad-Untitled"));
我不知何故需要将Functor存储为成员,以便我可以稍后在回调中调用它,但我不能只是模板化类,因为这需要我每次想要创建一个新的工具实例搜索一个不同的窗口(并且工具类除了EnumWindows之外还包含更多的函数)。Functor必须始终接受一个hWnd,然后可以使用它想要的任何东西对该数据进行操作,并且可以传递其他需要执行的操作(比如WindowName sting)。无论如何都存储了仿函数,而不是每次都要创建一个新的类实例。谢谢你的帮助
答案 0 :(得分:1)
解决方案由Piotr S发布。
Class Tools
{
public:
typedef std::function<bool(HWND)> WinFunctor;
std::vector<HWND> FindWindow(const WinFunctor& Functor);
private:
BOOL EnumWindowMsgProc(HWND hWnd);
static BOOL CALLBACK FreeWndProc(HWND hWnd, LPARAM lParam)
{
Tools* pThis = (Tools*)lParam;
return pThis->EnumWindowMsgProc(hWnd);
}
std::vector<HWND> m_Windows;
WinFunctor m_WinFunctor;
}
BOOL Tools::EnumWindowMsgProc(HWND hWnd)
{
if(m_WinFunctor(hWnd))
m_Windows.push_back(hWnd);
return TRUE;
}
std::vector<HWND> Tools::FindWindow(const WinFunctor& Functor)
{
m_Windows.clear();
m_WinFunctor=Functor;
EnumWindows(FreeWndProc, (LPARAM)this);
return m_Windows;
}
接口:
auto Windows = m_Tools.FindParentWindow(std::bind(&WinEnumFunctors::EnumByWindowName, std::placeholders::_1, L"Some WindowName"));