C# - 如何减少窗体的不透明度 onDeactivate 事件

C# - How to reduce Form's Opacity onDeactivate event

我的目的是减少不透明度 onDeactivate 事件,因为表单具有设置“保持在顶部”。

我试过这样做:

        protected override void OnDeactivate(EventArgs e)
        {
            base.OnDeactivate(e);
            Opacity = 0.7;
        }

一切正常(我单击另一个 window 并且我的表单的不透明度降低)直到我关闭表单。如果我关闭表单,我会收到此错误:

System.ComponentModel.Win32Exception (0x80004005): Parametro non corretto in System.Windows.Forms.Form.UpdateLayered() in System.Windows.Forms.Form.set_Opacity(Double value) in Hazar.Form1.OnDeactivate(EventArgs e) in C:\Users\lrena\source\repos\Hazar\Hazar\Form1.cs:riga 44 in System.Windows.Forms.Form.set_Active(Boolean value) in System.Windows.Forms.Form.WmActivate(Message& m) in System.Windows.Forms.Form.WndProc(Message& m) in Hazar.Form1.WndProc(Message& m) in C:\Users\lrena\source\repos\Hazar\Hazar\Form1.cs:riga 81 in System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) in System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) in System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

您遇到此异常是因为您正试图访问正在处理的控件的 属性。 Deactivate 事件也在 FormClosed 事件之后引发。意思是,在设置或调用任何 属性 或方法之前,您需要检查 OnDeactivate 委托中的 Control.Disposing 属性:

protected override void OnDeactivate(EventArgs e)
{
    base.OnDeactivate(e);

    if (!this.Disposing)
        Opacity = 0.7;
}

如果控件(在您的情况下是表单)已被处理,您还可以从 Control.IsDisposed 属性 中受益,其中 returns true。如果有的话,用它来检查 global/class 变量。