Exemplo n.º 1
0
        public void SetBits(Bitmap bitmap)
        {
            if (!Image.IsCanonicalPixelFormat(bitmap.PixelFormat) || !Image.IsAlphaPixelFormat(bitmap.PixelFormat))
            {
                throw new ApplicationException("图片必须是32位带Alhpa通道的图片。");
            }
            IntPtr oldBits  = IntPtr.Zero;
            IntPtr screenDC = FormStyleAPI.GetDC(IntPtr.Zero);
            IntPtr hBitmap  = IntPtr.Zero;
            IntPtr memDc    = FormStyleAPI.CreateCompatibleDC(screenDC);

            try
            {
                FormStyleAPI.Point         topLoc     = new FormStyleAPI.Point(Left, Top);
                FormStyleAPI.Size          bitMapSize = new FormStyleAPI.Size(Width, Height);
                FormStyleAPI.BLENDFUNCTION blendFunc  = new FormStyleAPI.BLENDFUNCTION();
                FormStyleAPI.Point         srcLoc     = new FormStyleAPI.Point(0, 0);

                hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
                oldBits = FormStyleAPI.SelectObject(memDc, hBitmap);

                blendFunc.BlendOp             = FormStyleAPI.AC_SRC_OVER;
                blendFunc.SourceConstantAlpha = Byte.Parse(((int)(Main.Opacity * 255)).ToString());
                blendFunc.AlphaFormat         = FormStyleAPI.AC_SRC_ALPHA;
                blendFunc.BlendFlags          = 0;

                FormStyleAPI.UpdateLayeredWindow(Handle, screenDC, ref topLoc, ref bitMapSize, memDc, ref srcLoc, 0, ref blendFunc, FormStyleAPI.ULW_ALPHA);
            }
            finally
            {
                if (hBitmap != IntPtr.Zero)
                {
                    FormStyleAPI.SelectObject(memDc, oldBits);
                    FormStyleAPI.DeleteObject(hBitmap);
                }
                FormStyleAPI.ReleaseDC(IntPtr.Zero, screenDC);
                FormStyleAPI.DeleteDC(memDc);
            }
        }