Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Usage:
- // BrushCursor brushCursor = null;
- // [...]
- // brushCursor = new BrushCursor();
- // someControl.Cursor = brushCursor.CreateCursor(Color.Red, 10);
- // [...]
- // someControl.Cursor = brushCursor.CreateCursor(Color.Blue, 3);
- // [...]
- // brushCursor.Dispose();
- // someControl.Cursor = Cursors.Default;
- using System;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Runtime.InteropServices;
- using System.Windows.Forms;
- public class BrushCursor : IDisposable
- {
- private Cursor currentCursor = null;
- public Cursor CreateCursor(Color color, int size)
- {
- if (currentCursor != null) Dispose();
- size += (size ^ 2) == 0 ? 0 : 1;
- size = Math.Max(Math.Min(size, 16), 2);
- currentCursor = CreateCursorInternal(CreateBitmap(color, size), new Point(16, 16));
- return currentCursor;
- }
- private static Cursor CreateCursorInternal(Bitmap bitmap, Point hotSpot)
- {
- var iconInfo = new ICONINFO(hotSpot, bitmap.GetHbitmap());
- IntPtr memPtr = Marshal.AllocHGlobal(Marshal.SizeOf(iconInfo));
- Marshal.StructureToPtr(iconInfo, memPtr, true);
- IntPtr curPtr = CreateIconIndirect(memPtr);
- DestroyIcon(memPtr);
- DeleteObject(iconInfo.hbmMask);
- DeleteObject(iconInfo.hbmColor);
- return new Cursor(curPtr);
- }
- private Bitmap CreateBitmap(Color color, int size)
- {
- var bitmap = new Bitmap(32, 32);
- var rect = new RectangleF(Point.Empty, bitmap.Size);
- using (var g = Graphics.FromImage(bitmap))
- using (var brush = new SolidBrush(color))
- using (var pen = new Pen(Color.FromArgb(48, 48, 48)) { DashStyle = DashStyle.Dot }) {
- // Clip the central region to support a transparent color
- g.SetClip(RectangleF.Inflate(rect, -8, -8), CombineMode.Exclude);
- g.DrawLine(pen, rect.Width / 2f, 0, rect.Width / 2f, rect.Height);
- g.DrawLine(pen, 0, rect.Height / 2f, rect.Width, rect.Height / 2f);
- g.ResetClip();
- var spot = new RectangleF(new PointF((32 - size) / 2, (32 - size) / 2), new SizeF(size, size));
- g.SmoothingMode = SmoothingMode.AntiAlias;
- g.FillEllipse(brush, spot);
- }
- return bitmap;
- }
- public void Dispose() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- protected virtual void Dispose(bool disposing) {
- currentCursor?.Dispose();
- currentCursor = null;
- }
- private struct ICONINFO {
- public bool fIcon;
- public int xHotspot;
- public int yHotspot;
- public IntPtr hbmMask;
- public IntPtr hbmColor;
- public ICONINFO(Point hotSpot, IntPtr hBitmap) {
- fIcon = false;
- xHotspot = hotSpot.X;
- yHotspot = hotSpot.Y;
- hbmMask = hBitmap;
- hbmColor = hBitmap;
- }
- }
- [DllImport("user32.dll", SetLastError = true)]
- private static extern IntPtr CreateIconIndirect(IntPtr iconInfo);
- [DllImport("user32.dll", SetLastError = true)]
- private static extern bool DestroyIcon(IntPtr hIcon);
- [DllImport("gdi32.dll")]
- private static extern bool DeleteObject(IntPtr hObject);
- }
Add Comment
Please, Sign In to add comment