In order to use the keyboard to control the cursor, you need to add WM_KEYDOWN and WM_KEYUP cases to the window function.
The statements in the WM_KEYDOWN case retrieve the current position of the cursor and update the position when an ARROW key is pressed. Add the following statements to the window function:
case WM_KEYDOWN:
GetCursorPos(&ptCursor);
if( wParam != VK_LEFT || wParam != VK_RIGHT ||
wParam != VK_UP || wParam != VK_DOWN )
break;
ScreenToClient(hWnd, &ptCursor);
repeat++; /* Increases the repeat rate */
switch(wParam) {
case VK_LEFT:
ptCursor.x -= repeat;
break;
case VK_RIGHT:
ptCursor.x += repeat;
break;
case VK_UP:
ptCursor.y -= repeat;
break;
case VK_DOWN:
ptCursor.y += repeat;
break;
default:
return (NULL);
}
GetClientRect(hWnd, &Rect); /* Gets the client boundaries */
if(ptCursor.x >= Rect.right)
ptCursor.x = Rect.right - 1;
else if(ptCursor.x < Rect.left)
ptCursor.x = Rect.left;
if(ptCursor.y >= Rect.bottom)
ptCursor.y = Rect.bottom - 1;
else if(ptCursor.y < Rect.top)
ptCursor.y = Rect.top;
ClientToScreen(hWnd, &ptCursor);
SetCursorPos(ptCursor.x, ptCursor.y);
break;
The GetCursorPos function retrieves the cursor position in screen coordinates. To check the position of the cursor within the client area, the coordinates are converted to client coordinates by using the ScreenToClient function. The switch statement checks for the ARROW keys; each time it encounters an ARROW key, the statement adds the current contents of the repeat variable to the appropriate coordinate of the cursor location.
The new position is checked to make sure it is still in the client area, using the GetClientRect function to retrieve the dimensions of the client area. The position is adjusted, if necessary. Finally, the ClientToScreen function converts the position back to screen coordinates and the SetCursorPos function sets the new position.
The WM_KEYUP case restores the initial value of the repeat variable when the user releases the key, as shown in the following example:
case WM_KEYUP:
repeat = 1; /* Clears the repeat count */
break;