Skip to main content
 首页 » 编程设计

c#之显示后的 Windows 窗体不透明度之C#

2024年02月24日17虾米姐

我正在尝试使用 C# 淡入一个 Windows 窗体,但在我显示该窗体后它似乎不起作用。显示表格后是否可以更改表格的不透明度?

代码:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
 
using System.Timers; 
 
namespace ToolStrip 
{ 
    public partial class Form1 : Form 
    { 
        Form ToolForm = new ToolForm(); 
        Form PropForm = new PropertyGrid(); 
 
        public Form1() 
        { 
            InitializeComponent(); 
        } 
 
        private void button1_Click(object sender, EventArgs e) 
        { 
            ToolForm.FormBorderStyle = FormBorderStyle.FixedToolWindow; 
            ToolForm.Owner = this; 
            ToolForm.Show(); 
            ToolForm.Location = new Point(50, 50); 
        } 
 
        private void button2_Click(object sender, EventArgs e) 
        { 
            PropForm.FormBorderStyle = FormBorderStyle.FixedToolWindow; 
            PropForm.Owner = this; 
            PropForm.Show(); 
            PropForm.Location = new Point(50, 50); 
 
            System.Timers.Timer aTimer = new System.Timers.Timer(10000); 
 
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
            aTimer.Interval = 2000; 
            aTimer.Enabled = true; 
 
            Console.WriteLine("Press the Enter key to exit the program."); 
            Console.ReadLine(); 
        } 
 
        private void OnTimedEvent(object source, ElapsedEventArgs e) 
        { 
            PropForm.Opacity = PropForm.Opacity - 0.25; 
            Console.WriteLine(PropForm.Opacity); 
        } 
    } 
} 

请您参考如下方法:

因为您使用的是 System.Timers.Timer,它是一个多线程计时器,在它的 OnTimedEvent() 中它调用另一个线程创建的控件,这会导致异常。

如果您使用 System.Windows.Forms.Timer,它将起作用。我测试了。