奇怪的显示窗口行为

时间:2012-11-23 13:48:38

标签: c windows winapi

当我拨打SetWindowPosMoveWindow时,我发现有一个窗口显示,我的意思是在我有机会呼叫WM_CREATE之前,窗口显示ShowWindow消息。经过一番检查后,我发现它与SetWindowRedraw有关。

以下是一个例子:

#include <Windows.h>
#include <windowsx.h>

LRESULT CALLBACK MainWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
BOOL MainWindow_OnCreate(HWND hWnd, LPCREATESTRUCT lpCreateStruct);
void MainWindow_OnDestroy(HWND hWnd);
void MainWindow_OnSize(HWND hWnd, UINT state, int cx, int cy);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
  WNDCLASSEX wcex = { sizeof(wcex) };
  HWND hWnd;
  BOOL ret;
  MSG msg;

  wcex.lpfnWndProc = MainWindowProc;
  wcex.hInstance = hInstance;
  wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
  wcex.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
  wcex.lpszClassName = TEXT("MainWindow");
  wcex.hIconSm = wcex.hIcon;

  RegisterClassEx(&wcex);
  hWnd = CreateWindow(wcex.lpszClassName, TEXT("Test"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_DESKTOP, NULL, hInstance, NULL);

  // ShowWindow(hWnd, nCmdShow);
  UpdateWindow(hWnd);

  while ((ret = GetMessage(&msg, NULL, 0, 0)) != 0)
  {
    if (ret == -1)
    {
      return 1;
    }
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  return msg.wParam;
}

LRESULT CALLBACK MainWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uMsg)
  {
    HANDLE_MSG(hWnd, WM_CREATE, MainWindow_OnCreate);
    HANDLE_MSG(hWnd, WM_DESTROY, MainWindow_OnDestroy);
    HANDLE_MSG(hWnd, WM_SIZE, MainWindow_OnSize);
  default:
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
  }
}

BOOL MainWindow_OnCreate(HWND hWnd, LPCREATESTRUCT lpCreateStruct)
{
  SetWindowPos(hWnd, NULL, 100, 100, 300, 300, SWP_NOREDRAW | SWP_NOZORDER);
  return TRUE;
}

void MainWindow_OnDestroy(HWND hWnd)
{
  PostQuitMessage(0);
}

void MainWindow_OnSize(HWND hWnd, UINT state, int cx, int cy)
{
  SetWindowRedraw(hWnd, FALSE);
  SetWindowRedraw(hWnd, TRUE);
  RedrawWindow(hWnd, NULL, NULL, RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN) ;
}

运行此选项,将显示一个窗口而不调用ShowWindow。但如果发表评论

SetWindowRedraw(hWnd, FALSE);
SetWindowRedraw(hWnd, TRUE);

然后窗口将保持隐藏状态。

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:2)

SetWindowRedraw()是一个将WM_SETREDRAW消息(使用SendMessage())发送到窗口的宏。

当窗口收到此类消息时,其样式集将添加WS_VISIBLE样式。

从MSDN(WM_SETREDRAW)逐字逐句:

  

[...]   如果应用程序将WM_SETREDRAW消息发送到隐藏窗口,   窗口变得可见(即操作系统添加了   WS_VISIBLE样式到窗口)。   [...]