首页 > 解决方案 > C# - 如何减少表单的不透明度 onDeactivate 事件

问题描述

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

我试图这样做:

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

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

System.ComponentModel.Win32Exception (0x80004005):C 中 Hazar.Form1.OnDeactivate(EventArgs e) 中 System.Windows.Forms.Form.set_Opacity(Double value) 中 System.Windows.Forms.Form.UpdateLayered() 中的参数不正确:\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) 在 C:\Users\lrena\source\repos\Hazar\Hazar\Form1.cs:riga 81 在 System.Windows.Forms System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 中的 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 中的 .Control.ControlNativeWindow.OnMessage(Message& m)

标签: c#event-handling

解决方案


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

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

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

如果控件(在您的情况下为表单)已被处置,您也可能会从Control.IsDisposed返回的属性中受益。true如果有的话,用它来检查全局/类变量。


推荐阅读