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

时间:2010-01-09 09:58:48

标签: c# winforms opacity

我正在尝试使用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);
        }
    }
}

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

使用你的代码(以及创建其他必要的Form类),我在第一次启动计时器并调用事件处理程序as Benny suggests时得到一个跨线程异常。

更改代码以检查计时器事件处理程序中的InvokeRequired,并在必要时使用Invoke更改PropForm.Opacity,导致在显示表单后不透明度发生变化,如必需的。

请注意,您可能希望从Opacity 0开始,然后逐渐增加 - 否则您的表单将完全开始并逐渐消失

我会顺便提一下,Opacity对某些版本的Windows没有任何影响,虽然你说你的Opacity效果在别处有效,所以在这种情况下不应该这样。

答案 2 :(得分:0)

我已经让它在没有计时器的情况下工作了:

        int Loop = 0;

        for (Loop = 100; Loop >= 5; Loop -= 10)
        {
            this.PropForm.Opacity = Loop / 95.0;
            this.PropForm .Refresh();
            System.Threading.Thread.Sleep(100);
        }

但我似乎无法将此示例更改为淡入而不是退出。