Sunday, August 22, 2010

Converting a Cursor to a Bitmap in .NET

I’ve been playing around with a little tool I’ve been developing and needed to display a Cursor in a PictureBox. There doesn’t seem to be built-in way to convert a Cursor to a Bitmap, which kind of makes sense since it might be an animated cursor so it wouldn’t be sensible to convert it to a Bitmap. I couldn’t find any examples on the web, so thought I’d post this code that does the trick.

          System.Windows.Forms.Cursor cursor = new System.Windows.Forms.Cursor(stream);
          Bitmap bitmap = new Bitmap(cursor.Size.Width, cursor.Size.Height);
          using (Graphics gBmp = Graphics.FromImage(bitmap))
          {
            cursor.Draw(gBmp, new Rectangle(0, 0, cursor.Size.Width, cursor.Size.Height));
            pictureBox.Image = bitmap;
          }

No comments: