2

我正在使用 Win32 API 创建窗口,这部分有问题:

GetMessage(&message, NULL, 0, 0);

我的问题是,当我尝试hwnd将要接收消息的第二个参数()更改为我之前制作的窗口时,它不起作用;例如,当我尝试关闭窗口时,它只会隐藏而不会关闭。

这是完整的代码:

#include <windows.h>

LRESULT CALLBACK WinProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow)
{
  WNDCLASS window;
  window.cbClsExtra = NULL;
  window.cbWndExtra = NULL;
  window.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
  window.hCursor = LoadCursor(hInst, IDC_ARROW);
  window.hIcon = NULL;
  window.hInstance = hInst;
  window.lpfnWndProc = WinProc;
  window.lpszClassName = "WINDOW";
  window.lpszMenuName = NULL;
  window.style = CS_HREDRAW | CS_VREDRAW;

  RegisterClass(&window);

  HWND hwnd = CreateWindow("WINDOW", "Win32 Window Application", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 200, 200, NULL, NULL, hInst, NULL);

  ShowWindow(hwnd, SW_SHOW);
  UpdateWindow(hwnd);

  MSG message;

  while (GetMessage(&message, NULL, 0, 0))
  {
    TranslateMessage(&message);
    DispatchMessage(&message);
  }

  return 1;
}

LRESULT CALLBACK WinProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam)
{
  switch (message)
  {
  case WM_CLOSE:
    {
      PostQuitMessage(0);
      break;
    }

  default:
    break;
  }

  return DefWindowProc(window, message, wParam, lParam);
}
4

1 回答 1

6

"... when I try to change the second parameter (hwnd) which is going to receive the messages to the window I previously made, it doesn't work."

Thread messages are not sent to a window; they're posted to the thread message queue with a NULL window handle, and will NOT be picked up with a GetMessage() loop tailored to a specific window handle.

Ex: PostQuitMessage() posts a thread message; not a window message. You need the NULL. From the GetMessage() docs:

If hWnd is NULL, GetMessage retrieves messages for any window that belongs to the current thread, and any messages on the current thread's message queue whose hwnd value is NULL (see the MSG structure). Therefore if hWnd is NULL, both window messages and thread messages are processed.

于 2014-04-26T11:44:29.673 回答