Click here to Skip to main content
Licence CPOL
First Posted 6 Sep 2011
Views 9,243
Downloads 885
Bookmarked 75 times

Creating a 'Progress Cursor'

By Pieter Van Parys | 11 Sep 2011
Utility to display a circular progressbar as cursor.
   4.89 (39 votes)

1

2

3
2 votes, 5.1%
4
37 votes, 94.9%
5
4.89/5 - 39 votes
μ 4.90, σa 1.00 [?]
 

cursor.png

Introduction

This article explains how we can customize the cursor to display a circular progress bar.

Class diagram

classdiagram.png

Using the code

Using the code is pretty simple, as you can see in 1-1.

var progressCursor = Van.Parys.Windows.Forms.CursorHelper.StartProgressCursor(100);

for (int i = 0; i < 100; i++)
{
 progressCursor.IncrementTo(i);

 //do some work
}

progressCursor.End();
1-1 Basic usage of ProgressCursor

The library also has some points of extensibility, by handling the 'EventHandler<CursorPaintEventArgs> CustomDrawCursor' event. By handling this event, the developer can choose to extend the default behaviour by running the DrawDefault method on the CursorPaintEventArgs instance (1-2).

...
progressCursor.CustomDrawCursor += progressCursor_CustomDrawCursor;
...

void progressCursor_CustomDrawCursor(object sender, 
                    ProgressCursor.CursorPaintEventArgs e)
{
	e.DrawDefault();
	
	//add text to the default drawn cursor
	e.Graphics.DrawString("Test", 
	           SystemFonts.DefaultFont, Brushes.Black, 0,0);
	
	//set Handled to true, or else nothing will happen,
	//and default painting is done
	e.Handled = true;
}
1-2 ProgressCursor extension using events

IProgressCursor also implements IDisposable, which makes the 'using' statement valid on this interface. The advantage is that no custom exception handling has to be done to ensure the End() method is called on the ProgressCursor. An example of the usage is found in 1-3.

using (var progressCursor = CursorHelper.StartProgressCursor(100))
{
    for (int i = 0; i < 100; i++)
    {
        progressCursor.IncrementTo(i);

        //simulate some work
    }
}
1-3 ProgressCursor implements IDisposable

Why implement IDisposable 

A classic usage of the default cursor classes would be like this:

private void DoStuff()
{
    Cursor.Current = Cursors.WaitCursor;

    try
    {
        //do heavy duty stuff here...
    }
    finally 
    {
        Cursor.Current = Cursors.Default;
    }
}

If one wouldn't implement the cursor change like this, the cursor could 'hang' and stay 'WaitCursor'. To avoid this Try Finally coding style, I implemented IDisposable on the IProgressCursor like this (2-2):

public ProgressCursor(Cursor originalCursor)
{
    OriginalCursor = originalCursor;
}

~ProgressCursor()
{
    Dispose();
}

public void Dispose()
{
    End();
}

public void End()
{
    Cursor.Current = OriginalCursor;
}
2-2 Classic sample of Cursor usage

How it works

Creating a custom cursor 

Basically, all the 'heavy lifting' is done by two imported user32.dll methods (1-3). These can be found in the class UnManagedMethodWrapper (what would be the right name for this class?).

public sealed class UnManagedMethodWrapper
{
	[DllImport("user32.dll")]
	public static extern IntPtr CreateIconIndirect(ref IconInfo iconInfo);

	[DllImport("user32.dll")]
	[return: MarshalAs(UnmanagedType.Bool)]
	public static extern bool GetIconInfo(IntPtr iconHandle, ref IconInfo iconInfo);
}
1-3 P/Invoke methods

These methods are called in CreateCursor (1-4):

private Cursor CreateCursor(Bitmap bmp, Point hotSpot)
{
	//gets the 'icon-handle' of the bitmap
	//(~.net equivalent of bmp as Icon)
	IntPtr iconHandle = bmp.GetHicon();
	IconInfo iconInfo = new IconInfo();
	
	//fill the IconInfo structure with data from the iconHandle
	UnManagedMethodWrapper.GetIconInfo(iconHandle, ref iconInfo);
	
	//set hotspot coordinates
	iconInfo.xHotspot = hotSpot.X;
	iconInfo.yHotspot = hotSpot.Y;
	
	//indicate that this is a cursor, not an icon
	iconInfo.fIcon = false;
	
	//actually create the cursor
	iconHandle = 
	  UnManagedMethodWrapper.CreateIconIndirect(ref iconInfo);
	
	//return managed Cursor object
	return new Cursor(iconHandle);
}
1-4 Cursor magic!

MSDN documentation:

Circular progress cursor drawing

int fontEmSize = 7;

var totalWidth = (int) Graphics.VisibleClipBounds.Width;
var totalHeight = (int) Graphics.VisibleClipBounds.Height;
int margin_all = 2;
var band_width = (int) (totalWidth*0.1887);

int workspaceWidth = totalWidth - (margin_all*2);
int workspaceHeight = totalHeight - (margin_all*2);
var workspaceSize = new Size(workspaceWidth, workspaceHeight);

var upperLeftWorkspacePoint = new Point(margin_all, margin_all);
var upperLeftInnerEllipsePoint = new Point(upperLeftWorkspacePoint.X + band_width, 
                                 upperLeftWorkspacePoint.Y + band_width);

var innerEllipseSize = new Size(((totalWidth/2) - upperLeftInnerEllipsePoint.X)*2, 
            ((totalWidth/2) - upperLeftInnerEllipsePoint.Y)*2);

var outerEllipseRectangle = 
    new Rectangle(upperLeftWorkspacePoint, workspaceSize);
var innerEllipseRectangle = 
    new Rectangle(upperLeftInnerEllipsePoint, innerEllipseSize);

double valueMaxRatio = (Value/Max);
var sweepAngle = (int) (valueMaxRatio*360);

var defaultFont = new Font(SystemFonts.DefaultFont.FontFamily, 
                           fontEmSize, FontStyle.Regular);
string format = string.Format("{0:00}", (int) (valueMaxRatio*100));
SizeF measureString = Graphics.MeasureString(format, defaultFont);
var textPoint = new PointF(upperLeftInnerEllipsePoint.X + 
  ((innerEllipseSize.Width - measureString.Width)/2), 
    upperLeftInnerEllipsePoint.Y + 
    ((innerEllipseSize.Height - measureString.Height)/2));

Graphics.Clear(Color.Transparent);

Graphics.DrawEllipse(BorderPen, outerEllipseRectangle);
Graphics.FillPie(FillPen, outerEllipseRectangle, 0, sweepAngle);

Graphics.FillEllipse(new SolidBrush(Color.White), innerEllipseRectangle);
Graphics.DrawEllipse(BorderPen, innerEllipseRectangle);

Graphics.DrawString(format, defaultFont, FillPen, textPoint); 

What does it (try to) solve

End users tend to have the impression to be waiting longer on a process with no progress visualization, then a process with progress indication. 

History

  • 2011-08-30: Initial version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Pieter Van Parys

Software Developer
SPHINX-IT
Belgium Belgium

Member

Follow on Twitter Follow on Twitter
LinkedIn Profile

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmembermanoj kumar choubey22:36 20 Feb '12  
QuestionWin32 handle passed to Cursor is not valid or is the wrong type. PinmemberMember 40789586:05 9 Dec '11  
GeneralGreat idea! Pinmemberdanlobo9:16 13 Oct '11  
Questionvery nice PinmemberCIDev7:06 11 Oct '11  
QuestionNice One PinmemberGandalf - The White3:15 10 Oct '11  
GeneralMy vote of 5 PinmemberOshtri Deka1:28 9 Oct '11  
GeneralRe: My vote of 5 PinmemberPieter Van Parys6:08 12 Oct '11  
QuestionVery good Pinmembermarc ochsenmeier10:35 19 Sep '11  
AnswerRe: Very good PinmemberPieter Van Parys1:23 20 Sep '11  
QuestionLove It! PinmemberNickPace14:05 8 Sep '11  
AnswerRe: Love It! PinmemberPieter Van Parys23:50 8 Sep '11  
GeneralAwesome! Pinmemberabdurahman ibn hattab3:00 7 Sep '11  
GeneralRe: Awesome! PinmemberPieter Van Parys7:13 7 Sep '11  
QuestionGreat stuff PinmemberKDME2:23 7 Sep '11  
AnswerRe: Great stuff PinmemberPieter Van Parys5:26 7 Sep '11  
QuestionMy vote of 5 PinmemberFilip D'haene0:36 7 Sep '11  
AnswerRe: My vote of 5 PinmemberPieter Van Parys7:14 7 Sep '11  
GeneralMy vote of 5 PinmemberAnkush Bansal0:33 7 Sep '11  
GeneralRe: My vote of 5 PinmemberPieter Van Parys7:14 7 Sep '11  
GeneralMy vote of 5 PinmemberScruffyDuck21:24 6 Sep '11  
GeneralRe: My vote of 5 PinmemberPieter Van Parys8:40 7 Sep '11  
QuestionGreat PinmemberWrangly9:36 6 Sep '11  
AnswerRe: Great PinmemberPieter Van Parys21:35 6 Sep '11  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120222.1 | Last Updated 12 Sep 2011
Article Copyright 2011 by Pieter Van Parys
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid