110,545
社区成员
发帖
与我相关
我的任务
分享
[DllImport("gdi32.dll", ExactSpelling = true)]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObj);
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
public static extern int UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref Point pptDst, ref Size psize, IntPtr hdcSrc, ref Point pptSrc, Int32 crKey, ref BLENDFUNCTION pblend, Int32 dwFlags);
public struct BLENDFUNCTION
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
public const byte AC_SRC_OVER = 0;
public const Int32 ULW_ALPHA = 2;
public const byte AC_SRC_ALPHA = 1;
[DllImport("user32.dll", ExactSpelling = true)]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern int DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern int DeleteObject(IntPtr hObj);
public void SetBits(Bitmap bitmap) {
if (!Bitmap.IsCanonicalPixelFormat(bitmap.PixelFormat) || !Bitmap.IsAlphaPixelFormat(bitmap.PixelFormat))
throw new ApplicationException("图片必须是32位带Alhpa通道的图片。");
IntPtr oldBits = IntPtr.Zero;
IntPtr screenDC = GetDC(IntPtr.Zero);
IntPtr hBitmap = IntPtr.Zero;
IntPtr memDc = CreateCompatibleDC(screenDC);
try {
Point topLoc = new Point(Left, Top);
Size bitMapSize = new Size(bitmap.Width, bitmap.Height);
BLENDFUNCTION blendFunc = new BLENDFUNCTION();
Point srcLoc = new Point(0, 0);
hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
oldBits = SelectObject(memDc, hBitmap);
blendFunc.BlendOp = AC_SRC_OVER;
blendFunc.SourceConstantAlpha = 255;
blendFunc.AlphaFormat = AC_SRC_ALPHA;
blendFunc.BlendFlags = 0;
UpdateLayeredWindow(Handle, screenDC, ref topLoc, ref bitMapSize, memDc, ref srcLoc, 0, ref blendFunc, ULW_ALPHA);
} finally {
if (hBitmap != IntPtr.Zero) {
SelectObject(memDc, oldBits);
DeleteObject(hBitmap);
}
ReleaseDC(IntPtr.Zero, screenDC);
DeleteDC(memDc);
}
}
protected override void OnHandleCreated(EventArgs e) {
InitializeStyles();
base.OnHandleCreated(e);
}
protected override CreateParams CreateParams {
get {
CreateParams cParms = base.CreateParams;
cParms.ExStyle |= 0x00080000; // WS_EX_LAYERED
return cParms;
}
}
private void InitializeStyles() {
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.UserPaint, true);
UpdateStyles();
}