问题是这样的: 我有两个winapi应用程序。沟通只有一种方式。 App1向App2发送消息。 App2应该接收WM_COPYDATA,其结构具有两个形状的坐标,然后它应该绘制这些形状。 收到消息。来自结构的数据是可以的。执行WM_COPYDATA案例中的代码应绘制窗口但没有任何反应(窗口只有纯白色背景)
发送消息如下所示:
HWND secondApp = FindWindowEx(NULL, NULL, _T("lab2app2"), NULL );
int error = GetLastError();
if(secondApp != 0) // window found, send message
{
// prepare data
FiguresData figuresData;
// Set Data About Location and dimensions of figures
// TODO
figuresData.square_origin_x = square_origin_x;
figuresData.square_origin_y = square_origin_y;
figuresData.circle_origin_x = circle_origin_x;
figuresData.circle_origin_y = circle_origin_y;
COPYDATASTRUCT data;
data.dwData = FIGURESDATA;
data.cbData = sizeof( figuresData );
data.lpData = &figuresData;
bool value = SendMessage(secondApp, WM_COPYDATA, (WPARAM)(HWND)mainWindow, (LPARAM)(LPVOID)&data);
}
数据数据结构很简单,只有4个整数。
App2接收消息和代码:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_PAINT:
RECT clientRectangle;
GetClientRect(hWnd, &clientRectangle);
hdc = BeginPaint(hWnd, &ps);
// nothing really here
EndPaint(hWnd, &ps);
break;
case WM_COPYDATA:
{
PCOPYDATASTRUCT pData;
pData = (PCOPYDATASTRUCT) lParam;
int square_origin_x = ((FiguresData *) ( pData->lpData ))->square_origin_x;
int square_origin_y = ((FiguresData *) ( pData->lpData ))->square_origin_y;
int circle_origin_x = ((FiguresData *) ( pData->lpData ))->circle_origin_x;
int circle_origin_y = ((FiguresData *) ( pData->lpData ))->circle_origin_y;
hdc = BeginPaint(hWnd, &ps);
HPEN oldPen = (HPEN)SelectObject(hdc, pen);
HBRUSH oldBrush = (HBRUSH)SelectObject(hdc, backgroundBrush);
COLORREF oldBackgroundColor = SetBkColor(hdc, backgroundColor);
Rectangle(hdc, square_origin_x, square_origin_y, square_origin_x+ SQUARE_SIDE, square_origin_y + SQUARE_SIDE);
Ellipse(hdc, circle_origin_x, circle_origin_y, circle_origin_x+ SQUARE_SIDE, circle_origin_y + SQUARE_SIDE);
// Put everything back the way we found it
SelectObject(hdc, oldPen);
SetBkColor(hdc, oldBackgroundColor);
EndPaint(hWnd, &ps);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
break;
}
return 0;
}
在调试器上我看到窗口句柄没问题。消息被App2发送和接收,并且WM_COPYDATA案例中的代码被执行但它没有任何效果。 在App2的窗口上没有绘制任何形状,我不知道为什么。任何线索?
答案 0 :(得分:1)
您在BeginPaint
处理程序之外调用WM_PAINT
。 BeginPaint
返回允许仅在窗口的无效区域上绘制的设备上下文。由于您尚未调用InvalidateRect
,因此窗口尚未生效,因此BeginPaint
不会绘制任何内容。
作为一般规则,您应该将绘画限制在WM_PAINT
处理程序中。让你的WM_COPYDATA
处理程序记住需要绘制的内容,然后使窗口无效并让WM_PAINT
处理程序实际绘制它。