Listing 1: caretbug.c Code to demonstrate caret bug
// caretbug.c -- program demonstrating SetCaretPos() problems #define WIN32_LEAN_AND_MEAN #include <windows.h> #define TEST_CLASS "CaretTest" LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); void OnKeyDown(HWND hwnd, UINT vk, int *x, int *y); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASS wndClass; MSG msg; HWND hwnd; (void)UNREFERENCED_PARAMETER(hPrevInstance); (void)UNREFERENCED_PARAMETER(lpCmdLine); (void)UNREFERENCED_PARAMETER(nCmdShow); ZeroMemory(&wndClass, sizeof(WNDCLASS)); wndClass.lpfnWndProc = WndProc; wndClass.hInstance = hInstance; wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); wndClass.lpszClassName = TEST_CLASS; if (!RegisterClass(&wndClass)) return(FALSE); hwnd = CreateWindow(TEST_CLASS, "Caret Bug Demo", WS_POPUPWINDOW | WS_CAPTION, 10, 10, 300, 300, GetDesktopWindow(), NULL, hInstance, NULL); if (hwnd != NULL) { ShowWindow(hwnd, SW_SHOWNORMAL); UpdateWindow(hwnd); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return(0); } LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static int x, y; PAINTSTRUCT ps; switch(uMsg) { case WM_CREATE: x = 10; y = 10; break; case WM_DESTROY: PostQuitMessage(0); break; case WM_PAINT: BeginPaint(hwnd, &ps); EndPaint(hwnd, &ps); return(0); case WM_SETFOCUS: CreateCaret(hwnd, NULL, 2, 20); SetCaretPos(x, y); ShowCaret(hwnd); break; case WM_KILLFOCUS: DestroyCaret(); break; case WM_KEYDOWN: OnKeyDown(hwnd, (UINT) wParam, &x, &y); break; } return(DefWindowProc(hwnd, uMsg, wParam, lParam)); } void OnKeyDown(HWND hwnd, UINT vk, int *x, int *y) { RECT r; BOOL valid; valid = TRUE; switch(vk) { case VK_LEFT: *x -= 15; break; case VK_RIGHT: *x += 15; break; case VK_UP: *y -= 15; break; case VK_DOWN: *y += 15; break; default: valid = FALSE; break; } if (valid) { GetClientRect(hwnd, &r); if (*x < r.left) *x = r.left; if (*x >= r.right) *x = r.right - 1; if (*y < r.top) *y = r.top; if (*y >= r.bottom) *y = r.bottom - 1; r.bottom = 20; InvalidateRect(hwnd, &r, TRUE); SetCaretPos(*x, *y); } } //End of File