Ejemplo n.º 1
0
        //cf. http://stackoverflow.com/a/1020819/1569
        internal static Bitmap GetCursor()
        {
            Windowing.CURSORINFO cursorInfo = new Windowing.CURSORINFO();
            cursorInfo.cbSize = Marshal.SizeOf(cursorInfo);
            if (!Windowing.GetCursorInfo(out cursorInfo))
            {
                return(null);
            }

            if (cursorInfo.flags != Windowing.CURSOR_SHOWING)
            {
                return(null);
            }

            IntPtr hicon = Windowing.CopyIcon(cursorInfo.hCursor);

            if (hicon == IntPtr.Zero)
            {
                return(null);
            }

            Windowing.ICONINFO iconInfo;
            if (!Windowing.GetIconInfo(hicon, out iconInfo))
            {
                return(null);
            }

            int x = cursorInfo.ptScreenPos.X - ((int)iconInfo.xHotspot);
            int y = cursorInfo.ptScreenPos.Y - ((int)iconInfo.yHotspot);

            using (Bitmap maskBitmap = Bitmap.FromHbitmap(iconInfo.hbmMask))
            {
                // Is this a monochrome cursor?
                if (maskBitmap.Height == maskBitmap.Width * 2)
                {
                    Bitmap resultBitmap = new Bitmap(maskBitmap.Width, maskBitmap.Width);

                    Graphics desktopGraphics = Graphics.FromHwnd(Windowing.GetDesktopWindow());
                    IntPtr   desktopHdc      = desktopGraphics.GetHdc();

                    IntPtr maskHdc = Windowing.CreateCompatibleDC(desktopHdc);
                    IntPtr oldPtr  = Windowing.SelectObject(maskHdc, maskBitmap.GetHbitmap());

                    using (Graphics resultGraphics = Graphics.FromImage(resultBitmap))
                    {
                        IntPtr resultHdc = resultGraphics.GetHdc();

                        // These two operation will result in a black cursor over a white background.
                        // Later in the code, a call to MakeTransparent() will get rid of the white background.
                        Windowing.BitBlt(resultHdc, 0, 0, 32, 32, maskHdc, 0, 32, Windowing.TernaryRasterOperations.SRCCOPY);
                        Windowing.BitBlt(resultHdc, 0, 0, 32, 32, maskHdc, 0, 0, Windowing.TernaryRasterOperations.SRCINVERT);

                        resultGraphics.ReleaseHdc(resultHdc);
                    }

                    IntPtr newPtr = Windowing.SelectObject(maskHdc, oldPtr);
                    Windowing.DeleteDC(newPtr);
                    Windowing.DeleteDC(maskHdc);
                    desktopGraphics.ReleaseHdc(desktopHdc);

                    // Remove the white background from the BitBlt calls,
                    // resulting in a black cursor over a transparent background.
                    resultBitmap.MakeTransparent(Color.White);
                    return(resultBitmap);
                }
            }

            Icon icon = Icon.FromHandle(hicon);

            return(icon.ToBitmap());
        }