Customized cursor in window controls (C#)

I wanted to show a big cross as a cursor in an image control when I wrote eDigitizer in C#. The big cross can help users to accurately digitize graphs. I searched the intenert and found some useful information. Based on the useful piece of information, I developed a class that can handle customized cursor – big blue cross. I will not explain it in detail. You can copy and paste it and use it in your project.

using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

namespace eDigitizer
{
	///

	/// Description of Cross.
	/// 

	public class Cross
	{
		Point crossPoint = new Point();
		Point currentPoint = new Point();
		Control myControl;

		public Cross()
		{
		}

		private void DrawCross2()
		{
			using (StreamWriter sw = new StreamWriter("trace.txt",true))
			{
				sw.WriteLine(crossPoint.ToString());
			}
			// draw a vertical line
			ControlPaint.DrawReversibleLine(myControl.PointToScreen(new Point(crossPoint.X,0)), myControl.PointToScreen(new Point(crossPoint.X, myControl.Height)), Color.Black);
			// draw a horizontal line
			ControlPaint.DrawReversibleLine(myControl.PointToScreen(new Point(0,crossPoint.Y)), myControl.PointToScreen(new Point(myControl.Width, crossPoint.Y)), Color.Black);
		}

		private void DrawCross(Point myPoint)
		{
	        // First DrawReversible to toggle to the background color
	        // Second DrawReversible to toggle to the specified color
		    if ((! crossPoint.IsEmpty) && (crossPoint != myPoint))
		    {
		    	DrawCross2();
		    }
			crossPoint = myPoint;
			DrawCross2();
		}

		public void Cross_OnMouseMove(Object sender, MouseEventArgs e)
		{
			myControl = (Control)sender;
			currentPoint.X = e.X;
			currentPoint.Y = e.Y;
			DrawCross(currentPoint);
		}

		public void Cross_OnMouseUp(Object sender, MouseEventArgs e)
		{
			DrawCross2();
		}
	}
}

The following private method demonstrates how to use the above class. It defines the size and shape of the customized cursor. You can call this method to attach the customized cursor to a window control during the window initiation.

private void CustomCursor(Control myControl)
{
	// create any bitmap
	int width = 518; //myControl.Width;
	int height = 518; //myControl.Height;
	Bitmap b    = new Bitmap(width,height);
	Graphics g  = Graphics.FromImage (b );
	// do whatever you wish
	Pen p = new Pen(Color.Blue, 1);
	g.DrawLine(p, new Point(0,height/2), new Point(width, height/2));
	g.DrawLine(p, new Point(width/2,0), new Point(width/2, height));
	// this is the trick!
	Cursor c = new Cursor(b.GetHicon());
	// attach cursor to the form
	myControl.Cursor = c;
	g.Dispose();
	p.Dispose();
	b.Dispose();
}

Download eDigitizer to see how it works.

  • Share/Bookmark

Leave a Response

You must be logged in to post a comment.