c - 为什么窗口不能正确设置光标?

标签 c winapi cursor

作为MSDN describes :

When the mouse moves over a window, the window receives a WM_SETCURSOR message (unless another window has captured the mouse).

If the application passes WM_SETCURSOR to DefWindowProc, the DefWindowProc function uses the following algorithm to set the cursor image:

  1. If the window has a parent, forward the WM_SETCURSOR message to the parent to handle.
  2. Otherwise, if the window has a class cursor, set the cursor to the class cursor.
  3. If there is no class cursor, set the cursor to the arrow cursor.

这是我的源代码:

#include <tchar.h>
#include <Windows.h>

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInsTance, LPTSTR lpCmdLine, int nCmdShow)
{
  WNDCLASSEX wcex = { 0 };
  HWND hWnd;
  BOOL ret;
  MSG msg;

  wcex.cbSize = sizeof(wcex);
  wcex.lpfnWndProc = WndProc;
  wcex.hInstance = hInstance;
  wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  // wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
  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))
  {
    if (ret == -1)
    {
      return EXIT_FAILURE;
    }
    else
    {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }
  return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uMsg)
  {
  case WM_DESTROY:
    PostQuitMessage(EXIT_SUCCESS);
    break;
  default:
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
  }
  return 0;
}

当我在窗口上快速移动光标时,光标并没有变成箭头,而是变成了调整大小的箭头;如果我将wcex.hCursor设置为LoadCursor(NULL, IDC_ARROW),一切都会好起来的。我的问题是:为什么我的代码不像 MSDN 所说的那样工作?

我的意思是,如果我不设置 wcex.hCursor,并且我不处理 WM_SETCURSOR 消息,那么 DefWindowProc 应该“将光标设置为箭头光标”,但似乎没有。这是为什么?

最佳答案

参见 WNDCLASSEXhCursor 成员的描述:

A handle to the class cursor. This member must be a handle to a cursor resource. If this member is NULL, an application must explicitly set the cursor shape whenever the mouse moves into the application's window.

WNDCLASSEX structure

关于c - 为什么窗口不能正确设置光标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11289833/

相关文章:

c - 传递字符数组的指针

c - Windows 线程 API : Calculate PI value with multiple threads

c - 使用 IPC 队列发送消息时,标识符已删除 (EIDRM) 错误

c - 将一种类型的值移动到另一种类型是否违反严格别名?

winapi - Windows API 中 HANDLE 和 HWND 的区别?

java - 在 WinAPI 调用漂亮的 char* 之后获取 GetLastError() 结果的最佳方法是什么?

android - 通过照片获取联系人信息的有效方法

winapi - 在 C++ Windows API 运行时调整窗口大小?

swift - 如何在 TextField 中设置 Cursor

javascript - 在Widget代码中没有jQuery的情况下使用光标图像向左滑动向右移动