How to: Show wait cursor in managed and native code

WaitCursor  Someone on the MSDN forum asked about how to show a wait cursor, like when your application is loading or performing some (background) task. It’s pretty simple to show the wait cursor in both managed and native code, and in this post we will see just how.

Managed Code (C#)

Set Cursor.Current to Cursors.WaitCursor, and call Cursor.Show(). And to come back to normal cursor, set Cursor.Current to Cursors.Default and call Show() again. Below is a button handler for a sample app that I made, (watch the video below)

private void button1_Click(object sender, EventArgs e)
{
    lblProgress.Text = "Downloading ether…";
    lblProgress.Update();

    Cursor.Current = Cursors.WaitCursor;
    Cursor.Show();

    //do some processing
    for (int i = 0; i < 50; i++)
    {
        progressBar1.Value = 2 * (i + 1);
        Thread.Sleep(100);
    }

    Cursor.Current = Cursors.Default;
    Cursor.Show();

    lblProgress.Text = "Download complete.";
    lblProgress.Update();
}

Native Code

In native code, call SetCursor(LoadCursor(NULL, IDC_WAIT)); to show the wait cursor; and SetCursor(LoadCursor(NULL, IDC_ARROW)); to come back to normal. The same button handler for native version of the app is below,

case IDC_BUTTON_DOWNLOAD:
    {
        HWND temp;

        temp = GetDlgItem(hDlg, IDC_STATIC_PROGRESS);
        SetWindowText(temp, L"Downloading ether…");
        UpdateWindow(temp);

        SetCursor(LoadCursor(NULL, IDC_WAIT));

        temp = GetDlgItem(hDlg, IDC_PROGRESSBAR);
        for (int i=0; i<50; i++)
        {
            SendMessage(temp, PBM_SETPOS, (i+1)*2, 0);
            Sleep(100);
        }

        SetCursor(LoadCursor(NULL, IDC_ARROW));

        temp = GetDlgItem(hDlg, IDC_STATIC_PROGRESS);
        SetWindowText(temp, L"Download Complete.");
        UpdateWindow(temp);
    }
    break;

Here is a video of the sample app running. First the managed version is deployed and the native version next,

Leave a Reply

Your email address will not be published. Required fields are marked *