/// <summary> /// Sets a form's opacity. /// </summary> /// <param name="form"></param> /// <param name="opacity"></param> /// <remarks> /// Note to implementors: This may be implemented as just "form.Opacity = opacity". /// This method works around some visual clumsiness in .NET 2.0 related to /// transitioning between opacity == 1.0 and opacity != 1.0.</remarks> public static void SetFormOpacity(Form form, double opacity) { if (opacity < 0.0 || opacity > 1.0) { throw new ArgumentOutOfRangeException("opacity", "must be in the range [0, 1]"); } uint exStyle = SafeNativeMethods.GetWindowLongW(form.Handle, NativeConstants.GWL_EXSTYLE); byte bOldAlpha = 255; if ((exStyle & NativeConstants.GWL_EXSTYLE) != 0) { uint dwOldKey; uint dwOldFlags; bool result = SafeNativeMethods.GetLayeredWindowAttributes(form.Handle, out dwOldKey, out bOldAlpha, out dwOldFlags); } byte bNewAlpha = (byte)(opacity * 255.0); uint newExStyle = exStyle; if (bNewAlpha != 255) { newExStyle |= NativeConstants.WS_EX_LAYERED; } if (newExStyle != exStyle || (newExStyle & NativeConstants.WS_EX_LAYERED) != 0) { if (newExStyle != exStyle) { SafeNativeMethods.SetWindowLongW(form.Handle, NativeConstants.GWL_EXSTYLE, newExStyle); } if ((newExStyle & NativeConstants.WS_EX_LAYERED) != 0) { SafeNativeMethods.SetLayeredWindowAttributes(form.Handle, 0, bNewAlpha, NativeConstants.LWA_ALPHA); } } GC.KeepAlive(form); }