Display images of the cursors avaiable in C#

Using a cursor in C# is easy. Simply set a control's Cursor property to the cursor you want to use.

Making images of cursors is a little harder because they don't show up on normal screen captures.

This example displays images of the available cursors. Each is shown in a PictureBox that uses the appropriate cursor so you can compare the images to the real thing. Some of the results don't match perfectly because the real cursor uses XOR mode drawing, animation, and other advanced graphics techniques that look nice in the cursor but that the cursor cannot draw perfectly.

For each cursor, the program calls the ShowCursor function to display the cursor's name and image inside a Panel control. The Panel is inside a FlowLayoutPanel control, which automatically arranges the Panels.

The interesting code is in the ShowCursor function.

// Display a cursor.
private void ShowCursor(string cursor_name, Cursor the_cursor)
{
// Make a Panel to hold the Label and PictureBox.
Panel pan = new Panel();
pan.Size = new Size(WID, HGT);
pan.Cursor = the_cursor;
flpSamples.Controls.Add(pan);

// Display the cursor's name in a Label.
Label lbl = new Label();
lbl.AutoSize = false;
lbl.Text = cursor_name;
lbl.Size = new Size(WID, 13);
lbl.TextAlign = ContentAlignment.MiddleCenter;
lbl.Location = new Point(0, 0);
pan.Controls.Add(lbl);

// Draw the cursor onto a Bitmap.
Bitmap bm = new Bitmap(BM_WID, BM_WID);
using (Graphics gr = Graphics.FromImage(bm))
{
the_cursor.Draw(gr, new Rectangle(0, 0, BM_WID, BM_WID));
}

// Display the Bitmap in a PictureBox.
PictureBox pic = new PictureBox();
pic.Location = new Point((WID - BM_WID) / 2, 15);
pic.BorderStyle = BorderStyle.Fixed3D;
pic.ClientSize = new Size(BM_WID, BM_WID);
pic.Image = bm;
pan.Controls.Add(pic);
}

This code makes a Panel containing a Label and a PictureBox, and sets their properties appropriately.

The most interesting part of the code is where it makes the cursor draw itself onto a Graphics object. That's the secret of displaying an image of the cursor.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.