1

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

3 回答 3

3

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

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

于 2010-01-09T10:13:17.947 回答
1

正如 Benny 建议的那样,使用您的代码(并创建其他必要的 Form 类),在第一次触发计时器并调用事件处理程序时,我得到了一个跨线程异常。

对代码进行更改以检查InvokeRequired计时器事件处理程序,并Invoke在必要时使用 change PropForm.Opacity,会在显示表单后根据需要更改不透明度。

请注意,您可能希望从Opacityof开始0,然后逐渐增加它 - 否则您的表单将开始完全稳定并逐渐淡出

我会顺便提一下,不透明度对某些版本的 Windows 没有影响,尽管你说你有不透明度效果在其他地方工作,所以在这种情况下不应该是这样。

于 2010-01-09T10:34:16.937 回答
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);
        }

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

于 2010-01-09T10:49:49.620 回答