如何使用计时器和/或while循环使标签显示一段时间

时间:2017-10-26 01:19:44

标签: c# loops timer enums

所以基本上我现在拥有的是一个带有隐藏标签的表单,我使用案例和一个简单的计数器(计算图片框上的点击)来移动案例。我需要做的是当我到达案例2时,我需要标签弹出一段时间(1秒左右),目标是让用户记住其中的2个并将其放入文本框中。我只是混淆了如何使用计时器或do while循环来使标签只弹出一段时间,就像它点击时只检查一次一样。我也使用枚举来存储"答案"但我并不是百分之百确定如何交叉检查用户输入的内容和枚举的内容。很抱歉,如果这是一个非常简单的答案,我对C#很新,尤其是循环和枚举。任何帮助将不胜感激。谢谢!

private void pbMummy_Click(object sender, EventArgs e)
    {
        counter++;

        switch (counter)
        {
            case 1:
                MessageBox.Show("Help me! I lost my passwords. Can you try and just get 2 of them?");
                break;

            case 2:

                    lblc1.Visible = true;
                    lblc2.Visible = true;
                    lblc3.Visible = true;
                    lblc4.Visible = true;
                    lblc5.Visible = true;

                    System.Threading.Thread.Sleep(1500);

                    lblc1.Visible = false;
                    lblc2.Visible = false;
                    lblc3.Visible = false;
                    lblc4.Visible = false;
                    lblc5.Visible = false;
                  break;

        }
    }

枚举

 public enum Memorize
    {
        boo92134,
        spooky93,
        grim432,
        fangs9981,
        cobweb439
    }

    public class Mummy
    {
        public Memorize answer { get; set; }

    }

2 个答案:

答案 0 :(得分:0)

您可以使用异步任务,因为它是一项非常简单的任务:

async void ShowLabelForCertainTime( Label label, int milliseconds )
{
   label.Visible = true;
   await Task.Delay( milliseconds ); //Time in milliseconds
   label.Visible = false;
}

只要你想要的话就打电话:

case 2:
   ShowLabelForCertainTime( lbcl1 );

答案 1 :(得分:0)

编辑:不知道为什么,但我一直在使用“按钮”而不是“标签”,但原理是相同的

您可以使用计时器将按钮设置为一段时间后可见。使用字典,以便您可以检索已启动事件的按钮。这是一个代码示例,只是作为概念的证明,它需要一些重构。

//run this on the click of the button
int button_id = 1; //or whatever way you want to reference your button
//myButtons[button_id].Visible = false;
var btnTimer = new System.Timers.Timer(2000);
btnTimer.Elapsed += myTestClass.HideButton;
btnTimer.Enabled = true;
//keep a reference to that button so you know who the timer belongs to
myTestClass.myTimers[btnTimer] = button_id;
public static class myTestClass
{
    public static Dictionary<System.Timers.Timer, int> myTimers = new Dictionary<System.Timers.Timer, int>();
    public static void HideButton(object sender, System.Timers.ElapsedEventArgs e)
    {
        System.Timers.Timer tmr = (System.Timers.Timer)sender;
        if(myTimers.ContainsKey(tmr))
        {
            //here you get your reference back to the button to which this timer belongs, you can show/hide it
            //var btn_id =  myButtons[myTimers[tmr]];
            //myButtons[btn_id].Visible = false;
            Console.WriteLine(myTimers[tmr]);
        }
        tmr.Enabled = false;
    }
}