我创建了一个 Subclass 类,并在其中SetWindowLongPtr()
设置GWLP_USERDATA
为包含指向派生类的指针,派生类用于分发消息。
因此,如果我使用SetWindowLongPtr(CurrentWindow, GWLP_USERDATA, (LONG_PTR)Data);
,当我不再想子类化时,如何恢复旧数据?MSDN说初始值为零,所以我应该使用SetWindowLongPtr(CurrentWindow, GWLP_USERDATA, (LONG_PTR)NULL);
函数吗?
编辑:我实际上使用 SetProp、GetProp、RemoveProp 找到了解决此问题的方法,现在我不必担心会弄乱其他功能。贝娄是我为可能需要它的人提供的代码:
#ifndef WIN32_SUBCLASS_CLASS_H
#define WIN32_SUBCLASS_CLASS_H
#include <Windows.h>
#include <tchar.h>
class SubclassWindow
{
public:
static LRESULT CALLBACK stWinSubclassHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
SubclassWindow* pWnd;
pWnd = (SubclassWindow*)GetProp(hwnd, TEXT("Subclass"));
if (pWnd)
return pWnd->WinSubclassHandler(hwnd, uMsg, wParam, lParam);
else
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
BOOL Subclass(SubclassWindow* Data, HWND hwnd)
{
if (Subclassed == TRUE || CurrentWindow != NULL)
return 0;
CurrentWindow = hwnd;
Subclassed = TRUE;
OriginalProc = (WNDPROC)GetWindowLongPtr(hwnd, GWL_WNDPROC);
SetProp(CurrentWindow, TEXT("Subclass"), (HANDLE)Data);
SetWindowLongPtr(CurrentWindow, GWL_WNDPROC, (LONG_PTR)SubclassWindow::stWinSubclassHandler);
return 1;
}
BOOL RemoveSubclass()
{
if (OriginalProc == NULL || CurrentWindow == NULL)
return 0;
Subclassed = FALSE;
RemoveProp(CurrentWindow, TEXT("Subclass"));
SetWindowLongPtr(CurrentWindow, GWL_WNDPROC, (LONG_PTR)OriginalProc);
return 1;
}
BOOL IsSubclassed() { return Subclassed; }
protected:
HWND CurrentWindow;
WNDPROC OriginalProc;
BOOL Subclassed;
SubclassWindow()
{
CurrentWindow = NULL;
OriginalProc = NULL;
Subclassed = FALSE;
}
virtual LRESULT CALLBACK WinSubclassHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) = 0;
};
#endif