protected virtual void UpdateLayeredWindow(byte alpha) { var bitmap = (Bitmap)BackgroundImage; IntPtr hdcScreen = NativeMethods.GetDC(new HandleRef(this, IntPtr.Zero)); IntPtr hdcMemory = NativeMethods.CreateCompatibleDC(new HandleRef(this, hdcScreen)); IntPtr hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); IntPtr hOldBitmap = NativeMethods.SelectObject(new HandleRef(this, hdcMemory), new HandleRef(this, hBitmap)); var size = new NativeMethods.SIZESTRUCT(bitmap.Width, bitmap.Height); var pointSource = new NativeMethods.POINTSTRUCT(0, 0); var topPos = new NativeMethods.POINTSTRUCT(Left, Top); var blend = new NativeMethods.BLENDFUNCTION(); blend.BlendOp = 0; blend.BlendFlags = 0; blend.SourceConstantAlpha = alpha; blend.AlphaFormat = 1; NativeMethods.UpdateLayeredWindow(handle, hdcScreen, ref topPos, ref size, hdcMemory, ref pointSource, 0, ref blend, 0x00000002); NativeMethods.ReleaseDC(new HandleRef(this, IntPtr.Zero), new HandleRef(this, hdcScreen)); if (hBitmap != IntPtr.Zero) { NativeMethods.SelectObject(new HandleRef(this, hdcMemory), new HandleRef(this, hOldBitmap)); NativeMethods.DeleteObject(new HandleRef(this, hBitmap)); } NativeMethods.DeleteDC(new HandleRef(this, hdcMemory)); }
public void SetBits() { Bitmap image = new Bitmap(this.m_HostForm.Width + (m_Config.ShadowWidth * 2), this.m_HostForm.Height + (m_Config.ShadowWidth * 2)); Graphics g = Graphics.FromImage(image); g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; this.DrawShadow(g); if (Image.IsCanonicalPixelFormat(image.PixelFormat) && Image.IsAlphaPixelFormat(image.PixelFormat)) { IntPtr zero = IntPtr.Zero; //diff //IntPtr dC = NativeMethods.GetDC(new HandleRef(null, IntPtr.Zero)); IntPtr dC = NativeMethods.GetDC(IntPtr.Zero); IntPtr hgdiobj = IntPtr.Zero; //diff //IntPtr hdc = NativeMethods.CreateCompatibleDC(new HandleRef(null, dC)); IntPtr hdc = NativeMethods.CreateCompatibleDC(dC); try { NativeMethods.POINTSTRUCT pptDst = new NativeMethods.POINTSTRUCT(base.Left, base.Top); NativeMethods.SIZESTRUCT psize = new NativeMethods.SIZESTRUCT(base.Width, base.Height); NativeMethods.BLENDFUNCTION pblend = new NativeMethods.BLENDFUNCTION(); NativeMethods.POINTSTRUCT pprSrc = new NativeMethods.POINTSTRUCT(0, 0); hgdiobj = image.GetHbitmap(Color.FromArgb(0)); zero = NativeMethods.SelectObject(hdc, hgdiobj); pblend.BlendOp = 0; pblend.SourceConstantAlpha = byte.Parse("255"); pblend.AlphaFormat = 1; pblend.BlendFlags = 0; NativeMethods.UpdateLayeredWindow(base.Handle, dC, ref pptDst, ref psize, hdc, ref pprSrc, 0, ref pblend, 2); return; } finally { if (hgdiobj != IntPtr.Zero) { NativeMethods.SelectObject(hdc, zero); NativeMethods.DeleteObject(hgdiobj); } NativeMethods.ReleaseDC(IntPtr.Zero, dC); NativeMethods.DeleteDC(hdc); } } throw new ApplicationException("图片必须是32位带Alhpa通道的图片。"); }