Set cursor for a form and have it reset automatically

PlausiblyDamp

Administrator
Joined
Sep 4, 2002
Messages
6,155
Location
Lancashire, UK
User Rank
*Expert*
Little class inspired by a code snippet from Nerseus originally posted here

this C# class will set the Cursor for a given form and reset it when the class is disposed - propbably best used with C#s using function.

Sample usage
C#:
//following line will set the mouse pointer to the hourglass
using (ChangeMousePointer c = new ChangeMousePointer(this))
	{
	for (int i=0;i < 1000000; i++)
		Application.DoEvents();
	} //cursor will be restored here

The class also provides an overloaded constructor allowing you to specify which cursor is required.

In a debug build the class runs slower as it will record which Method / File / Line it was allocated on (Using the StackTrace and StackFrame classes) and has a finalizer that checks we have been properly disposed - if not it will assert giving the relevant details about its creation.
In a release build all this information is removed and no Finalizer is emitted.

Typical assert output is as follows
Code:
---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
ChangeMousePointer not disposed
---- Assert Long Message ----
Originally allocated 
Method : button2_Click
File : c:\documents and settings\x\my documents\visual studio projects\windowsapplication7\form1.cs
Line : 117

    at ChangeMousePointer.Finalize()

The class can be used for VB you just have to remember to call .Dispose manually (VB doesnt have the equivalent of C#s using)

Edit: In debug builds now asserts if the cursor has been changed to a different cursor in between the object being created and disposed.
 

Attachments

Last edited by a moderator:
Back
Top