【问题标题】:Timer in WinFormsWinForms 中的计时器
【发布时间】:2014-09-03 09:53:55
【问题描述】:

我正在使用计时器来创建启动画面。 我想做的是使表单淡入淡出。我首先在表单的构造函数中将表单透明度设为 0,然后在表单加载方法中触发计时器。 现在在我的Timer_Tick 方法中,我不断增加不透明度,比如说,0.2。 我想一旦计时器达到其间隔的一半,我就会开始降低不透明度,但我无法做到这一点。

我不太清楚定时器是如何工作的,但我想实现这样的东西:

if(Whatever_Timer_Value_Is <= Interval/2)  //Can't achieve this :s
this.Opacity += 2;
else
this.Opacity -=2 ;

那么..有没有办法随时获取 Timer 的值?或者有没有其他方法可以做到这一点? 请保持简单。我只是个业余爱好者。 X(

【问题讨论】:

  • 以可以递增的形式创建一个计数器变量并在滴答事件中检查。还要检查值的不透明度范围!
  • 进展顺利。谢谢=D

标签: c# winforms timer


【解决方案1】:

试试这个postServy建议的方法。我已经修改了表单淡出的方法来隐藏表单。

public Form1()
{
    InitializeComponent();
    this.Opacity = 0;
}


private void Form1_Load(object sender, EventArgs e)
{            
    ShowMe();
}


private void button1_Click(object sender, EventArgs e)
{
    HideMe();

}

private void ShowMe()
{
    int duration = 1000;//in milliseconds
    int steps = 100;
    Timer timer = new Timer();
    timer.Interval = duration / steps;

    int currentStep = 0;
    timer.Tick += (arg1, arg2) =>
    {
        Opacity = ((double)currentStep) / steps;
        currentStep++;

        if (currentStep >= steps)
        {
            timer.Stop();
            timer.Dispose();
        }
    };

    timer.Start();
}
private void HideMe()
{
    int duration = 1000;//in milliseconds
    int steps = 100;
    Timer timer = new Timer();
    timer.Interval = duration / steps;

    int currentStep = 100;
    timer.Tick += (arg1, arg2) =>
    {
        Opacity = ((double)currentStep) / steps;
        currentStep--;

        if (currentStep <= 0)
        {
            timer.Stop();
            timer.Dispose();
            this.Close();
        }
    };

    timer.Start();
}

【讨论】:

    【解决方案2】:

    只需记住启动计时器的时间即可。这样你就总能知道过去了多少时间。

    您可以为此使用Environment.TickCount。这是一个单调的时钟。

    在计时器中应避免增量计算(如Opacity += 0.2;),因为不能保证接收所有滴答声或在正确的时间点接收它们。您最好计算过去了多少时间并从中计算出正确的不透明度值。

    【讨论】:

      【解决方案3】:

      尝试为启动创建第二个表单:

      Form splash = new Form();
      
      public Form1()
      {
          InitializeComponent();
          this.Visible = false;
          splash.Opacity = 0;
          splash.Show();
          _timerShow();
          _timerHide();
          this.Visible = true;
      }
      
      private async void _timerShow()
      {
          while(splash.opacity!=1)
          {
              await Task.Delay(50);
              splash.opacity +=.01;
          }
      }
      
      private async void _timerHide()
      {
          while(splash.opacity!=0)
          {
              await Task.Delay(50);
              splash.opacity -=.01;
          }
      }
      

      【讨论】:

        【解决方案4】:

        【讨论】:

        • 这就是我开始的地方。但是因为它对我来说太复杂了,所以我试图把它分解;这就是我卡住的地方。
        猜你喜欢
        • 2011-08-02
        • 2010-11-13
        • 2015-05-13
        • 2017-03-29
        • 2022-01-06
        • 2020-11-14
        • 2015-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多