当用户拖动 OLE 对象时,我需要更改窗口的背景画笔。
我的代码如下。
实际上被称为SetClassLongA
。 hWnd
、DragBrush
都可以。
但是窗口的背景
hWnd
没有改变。我做错了什么?
使用
SetClassLongA
来更改窗口背景是否正确?
// IDropTarget implementation
virtual HRESULT __stdcall DragEnter(IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) override {
std::cout << " OLE -> DragEnter." << std::endl;
*pdwEffect = DROPEFFECT_COPY;
HBRUSH DragBrush = CreateHatchBrush(HS_CROSS, RGB(255, 0, 0));
if (DragBrush == NULL) {
std::cout << "Error creating dragging brush_2" << std::endl;
}
DWORD OldBrush = SetClassLongA(hWnd, GCLP_HBRBACKGROUND, (LONG) DragBrush);
BOOL ok1 = InvalidateRect(hWnd, NULL, TRUE);
BOOL ok2 = UpdateWindow(hWnd);
// ok1=ok2=1 OK
return S_OK;
}
可以看到备注,上面写着:谨慎使用SetClassLong函数。例如,可以使用 SetClassLong 更改类的背景颜色,但此更改不会立即重新绘制属于该类的所有窗口。
所以需要使用
GetClientRect
和FillRect
来重绘客户区。
我使用了Visual Studio的项目示例。看,这是重画之前的紫色窗口:
当我们添加
GetClientRect
和 FillRect
时。当我阅读时它显示了正确的颜色:
WM_PAINT消息中的代码:
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
HBRUSH hBrush = CreateSolidBrush(RGB(220, 0, 0));
ULONG_PTR res = SetClassLongPtr(hWnd, GCLP_HBRBACKGROUND, (LONG)hBrush);
//DeleteObject(hBrush);
RECT rect;
GetClientRect(hWnd, &rect);
int res1= FillRect(hdc, &rect, hBrush);
EndPaint(hWnd, &ps);
}