08 March 2006

AutoWaitCursor Class

If you've ever had to deal with turning the "wait" cursor on and off within your Windows Forms application then you've undoubtedly wished there was a better way.

The typical approach is to set the Cursor property for the current form to Cursors.WaitCursor at the beginning of a long-running process and then resetting it back to Cursors.DefaultCursor when the process has finished. You might even set the default cursor within a Finally block in case an exception is raised so as to prevent leaving the cursor in a "wait" state.

I've noticed that no matter how diligent you are, you almost always end up with the cursor out of sync at some point (e.g. your "wait" cursor doesn't display when it should or it displays when it shouldn't).

What if you could have your application automatically display the "wait" cursor at the appropriate time and then have it automatically reset back to the default cursor when the process has completed. Well, you can. During some research on this subject, I came across a custom class, AutoWaitCursor, that does just that.

Without going into the nitty gritty details (click the above link for the original source code and description), the idea is that the AutoWaitCursor class ties into the application's OnIdle event to determine when a long-running process is running. You only need to add a single line (using the version I've posted below - otherwise, you'll need at least two lines) of code to your application's main form's Load event to have your cursor change automatically.

For my current project, I had to convert the AutoWaitCursor class to VB.Net (the original is in C#). Click here to view the VB.Net source code.

Follow Up: I entered this as a suggested feature on the MSDN Product Feedback Center. If anyone else has any interest in seeing this become an intrinsic feature of the .Net Framework, click here to vote.

1 comment:

Anonymous said...

It seems like this code causes our main application to lose focus. At times, another window (IE or Word or anything else) will take focus and put our application in the background. Has anyone else had this problem?

Post a Comment