[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Draw a cursor and use it at run time in C#

[Draw a cursor and use it at run time in C#]

It's not too hard to draw a cursor and use it in a C# program. The basic approach is to create a Bitmap and then create a new Cursor object, passing its constructor the Bitmap object's icon handle as given by its GetHicon method.

When the example starts, it uses the following code to draw a cursor that displays two diamonds. The inner diamond is opaque and the outer diamond is translucent. (If you look closely at the picture, you'll see the background image showing through the outer diamond.)

private void Form1_Load(object sender, EventArgs e) { // Fit the background image. this.ClientSize = this.BackgroundImage.Size; // Draw the cursor image. const int wid = 63; const int hgt = 63; Bitmap bm = new Bitmap(wid, hgt); using (Graphics gr = Graphics.FromImage(bm)) { gr.Clear(Color.Transparent); int cx = wid / 2; int cy = hgt / 2; Point[] outer_points = { new Point(cx, 0), new Point(2 * cx, cy), new Point(cx, 2 * cy), new Point(0, cy), }; using (SolidBrush br = new SolidBrush(Color.FromArgb(128, 255, 255, 0))) { gr.FillPolygon(br, outer_points); } gr.DrawPolygon(Pens.Red, outer_points); Point[] inner_points = { new Point(cx, cy - 6), new Point(cx + 6, cy), new Point(cx, cy + 6), new Point(cx - 6, cy), }; gr.FillPolygon(Brushes.LightBlue, inner_points); gr.DrawPolygon(Pens.Blue, inner_points); } // Turn the bitmap into a cursor. this.Cursor = new Cursor(bm.GetHicon()); }

The code defines constants to represent the cursor's width and height. This example uses a 63 x 63 pixel cursor, but you can change those values to see what happens.

Next, the program creates a Bitmap of the desired size and a Graphics object to work with the Bitmap. It clears the Bitmap with the Transparent color so parts of the Bitmap that the program doesn't draw on are invisible in the cursor.

The code then defines a large diamond. It fills the diamond with translucent yellow and then outlines the diamond in red.

Next, the code defines a smaller dialog, fills it with light blue, and outlines it in blue.

Finally, the program sets the form's cursor to a new Cursor object created from the Bitmap. (That line is highlighted in blue.)

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.