예제 #1
0
        public static Cursor CreateCursorFromBitmap(Bitmap bitmap, byte alphaLevel, Point hotSpot)
        {
            Bitmap cursorBitmap = null;

            External.ICONINFO iconInfo  = new External.ICONINFO();
            Rectangle         rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            try
            {
                // Here, the premultiplied alpha channel is specified
                cursorBitmap = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format32bppPArgb);

                // I'm assuming the source bitmap can be locked in a 24 bits per pixel format
                BitmapData bitmapData       = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                BitmapData cursorBitmapData = cursorBitmap.LockBits(rectangle, ImageLockMode.WriteOnly, cursorBitmap.PixelFormat);

                // Use either SafeCopy() or UnsafeCopy() to set the bitmap contents
                SafeCopy(bitmapData, cursorBitmapData, alphaLevel);
                //UnsafeCopy(bitmapData, cursorBitmapData, alphaLevel);

                cursorBitmap.UnlockBits(cursorBitmapData);
                bitmap.UnlockBits(bitmapData);

                if (!External.GetIconInfo(bitmap.GetHicon(), out iconInfo))
                {
                    throw new Exception("GetIconInfo() failed.");
                }

                iconInfo.xHotspot = hotSpot.X;
                iconInfo.yHotspot = hotSpot.Y;
                iconInfo.IsIcon   = false;

                //IntPtr cursorPtr = External.CreateIconIndirect(ref iconInfo);
                SafeIconHandle cursorPtr = External.CreateIconIndirect1(ref iconInfo);
                //if (cursorPtr == IntPtr.Zero)
                //    throw new Exception("CreateIconIndirect() failed.");

                return(CursorInteropHelper.Create(cursorPtr));
                //return (new Cursor(cursorPtr));
            }
            finally
            {
                if (cursorBitmap != null)
                {
                    cursorBitmap.Dispose();
                }
                if (iconInfo.ColorBitmap != IntPtr.Zero)
                {
                    External.DeleteObject(iconInfo.ColorBitmap);
                }
                if (iconInfo.MaskBitmap != IntPtr.Zero)
                {
                    External.DeleteObject(iconInfo.MaskBitmap);
                }
            }
        }
예제 #2
0
 override protected bool ReleaseHandle()
 {
     return(External.DestroyIcon(handle));
 }