C# SetOpacity / 設定視窗透明度,
先行調用“取視窗屬性 /GetWindowLong”取得視窗的“視窗擴充風格 /GWL_EXSTYLE”屬性值,位或(bor)“視窗擴充分層 /WS_EX_LAYERED”屬性值,後調用“置視窗屬性 /SetWindowLong”設定新的ExStyle“置視窗分層透明度/ SetLayeredWindowAttributes”後傳遞“Alpha /LWA_ALPHA”透明表單 具體參照MSDN
protected override void OnLoad(EventArgs e){ // base.Opacity = 0.9f; SetOpacity((int)base.Handle, (255 / 100) * 90);}
上面的範例程式碼兩者功能相同,設定視窗透明度
private static void SetOpacity(int hWnd, byte bAlpha) { int dwExStyle = NativeMethod.GetWindowLong(hWnd, NativeMethod.GWL_EXSTYLE); dwExStyle |= NativeMethod.WS_EX_LAYERED; NativeMethod.SetWindowLong(hWnd, NativeMethod.GWL_EXSTYLE, dwExStyle); if (!NativeMethod.SetLayeredWindowAttributes(hWnd, 0, bAlpha, NativeMethod.LWA_ALPHA)) throw new Exception("Unable to set the Window Opacity."); }
public abstract class NativeMethod { [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetLayeredWindowAttributes(int hwnd, int crKey, byte bAlpha, int dwFlags); [DllImport("user32.dll", SetLastError = true)] public static extern int GetWindowLong(int hwnd, int nlndex); [DllImport("user32.dll", SetLastError = true)] public static extern int SetWindowLong(int hwnd, int nlndex, int dwNewLong); public const int LWA_ALPHA = 2; public const int LWA_COLORKEY = 1; public const int GWL_EXSTYLE = -20; public const int WS_EX_TRANSPARENT = 32; public const int WS_EX_LAYERED = 524288; }
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。