Using the Keyboard to Move the Cursor

Because Windows does not require a mouse, an application should be able to simulate mouse actions with the keyboard. The following example shows how to achieve this, by using the GetCursorPos and SetCursorPos functions, and by processing input from the arrow keys.

HCURSOR hCurs1, hCurs2; // cursor handles

POINT pt; // cursor location

RECT rc; // client area coordinates

static int repeat = 1; // repeat key counter

//

// Other declarations and initialization.

//

switch (message)

{

//

// Process other messages.

//

case WM_KEYDOWN:

if (wParam != VK_LEFT && wParam != VK_RIGHT &&

wParam != VK_UP && wParam != VK_DOWN)

{

break;

}

GetCursorPos(&pt);

// Convert screen coordinates to client coordinates.

ScreenToClient(hwnd, &pt);

switch (wParam)

{

// Move the cursor to reflect which

// arrow keys are pressed.

case VK_LEFT: // left arrow

pt.x -= repeat;

break;

case VK_RIGHT: // right arrow

pt.x += repeat;

break;

case VK_UP: // up arrow

pt.y -= repeat;

break;

case VK_DOWN: // down arrow

pt.y += repeat;

break;

default:

return NULL;

}

repeat++; // increment repeat count

// Keep the cursor in the client area.

GetClientRect(hwnd, &rc);

if (pt.x >= rc.right)

{

pt.x = rc.right - 1;

}

else

{

if (pt.x < rc.left)

{

pt.x = rc.left;

}

}

if (pt.y >= rc.bottom)

pt.y = rc.bottom - 1;

else

if (pt.y < rc.top)

pt.y = rc.top;

// Convert client coordinates to screen coordinates.

ClientToScreen(hwnd, &pt);

SetCursorPos(pt.x, pt.y);

break;

case WM_KEYUP:

repeat = 1; // clear repeat count

break;

}