6.2.3 Example: Displaying the Hourglass During a Lengthy Operation

Whenever your application begins a lengthy operation, such as reading or writing a large block of data to a disk file, it should change the shape of the cursor to an hourglass. This lets users know that a lengthy operation is in progress and that they should wait before attempting to continue their work. After the operation is complete, your application should restore the cursor to its previous shape.

To change the cursor to an hourglass, use the following statements:

HCURSOR hSaveCursor;
HCURSOR hHourGlass;
    .
    .
    .

hHourGlass = LoadCursor(NULL, IDC_WAIT);
    .
    .
    .

SetCapture(hWnd);
hSaveCursor = SetCursor(hHourGlass);

/* Lengthy operation */

SetCursor(hSaveCursor);
ReleaseCapture();
    .
    .
    .

In this example, the application defines the variables that will be used to store the cursor handles. Both variables are type HCURSOR. After defining variables, the application first captures the mouse input, using the SetCapture function. This keeps the user from attempting to use the mouse to carry out work in another application while the lengthy operation is in progress. Once the application has captured the mouse input, Windows directs all mouse input messages to the specified window, regardless of whether the mouse is in that window. The application can then process the messages as appropriate.

After capturing the mouse input, the application then changes the cursor shape by using the SetCursor function. SetCursor returns a handle to the previous cursor shape, so that the shape can be restored later. The application saves this handle in the variable hSaveCursor. After the lengthy operation is complete, the application restores the previous cursor shape.

Finally, the ReleaseCapture function releases the mouse input.