6.4.2 Using the Cursor When No Mouse Is Available

When no mouse is available, the application must display and move the cursor in response to keyboard actions. To determine whether a mouse is present, use the GetSystemMetrics function and specify the SM_MOUSEPRESENT constant, as follows:

GetSystemMetrics(SM_MOUSEPRESENT);

This function returns a nonzero value if the mouse is present.

You will need to display the cursor and update its position when the application is activated; when the application is deactivated, you will need to hide the cursor. The following statements carry out both activation functions:

case WM_ACTIVATE:
    if (!GetSystemMetrics(SM_MOUSEPRESENT)) {
        if (!HIWORD(lParam)) {
            if (wParam) {
                SetCursor(hMyCursor);
                ClientToScreen(hWnd, &ptCursor);
                SetCursorPos(ptCursor.x, ptCursor.y);
            }
            ShowCursor(wParam);
        }
    }
    break;

In this example, the cursor functions are called only if no mouse is available; that is, if the GetSystemMetrics function returns FALSE. Since Windows positions and updates the cursor automatically if a mouse is present, the cursor functions, if carried out, would disrupt this processing.

The next step is to determine whether the window is minimized (an icon). The cursor must not be displayed or updated if the window is an icon. In a WM_ACTIVATE message, the high-order word is nonzero if the window is minimized, so the cursor functions are called only if this value is zero.

The final step is to check the wParam parameter to determine whether the window is being activated or deactivated. This parameter is nonzero if the window is being activated. When a window is activated, the SetCursor function sets the cursor shape and the SetCursorPos function positions the cursor. The ClientToScreen function converts the cursor position to screen coordinates, as required by SetCursorPos. Finally, the ShowCursor function shows or hides the cursor, depending on the value of wParam.

When the system has no mouse installed, applications must be careful when using the cursor. In general, applications must hide the cursor when the window is closed, destroyed, or relinquishes control. If an application fails to hide the cursor, it prevents subsequent windows from using the cursor. For example, if an application sets the cursor to the hourglass, displays the cursor, then relinquishes control to a dialog box, the cursor remains on the screen (possibly in a new shape) but cannot be used by the dialog box.