将标签文本显示为警告消息并在几秒钟后隐藏它?

时间:2013-04-11 14:40:06

标签: c# .net winforms

我有一些按钮可以验证用户是否是管理员。如果用户当前登录不是管理员,则标签将显示为警告消息,然后在几秒钟后隐藏。我在警告消息后尝试使用lblWarning.Hide();lblWarning.Dispose();,但问题是,它甚至在显示警告消息之前隐藏了消息。这是我的代码。

private void button6_Click(object sender, EventArgs e)
{
    if (txtLog.Text=="administrator")
    {
        Dialog();
    }

    else
    {
       lblWarning.Text = "This action is for administrator only.";
       lblWarning.Hide();
    }

}

5 个答案:

答案 0 :(得分:26)

你想要用Timer“隐藏”它。你可以实现这样的东西:

var t = new Timer();
t.Interval = 3000; // it will Tick in 3 seconds
t.Tick += (s, e) =>
{
    lblWarning.Hide();
    t.Stop();
};
t.Start();

而不是:

lblWarning.Hide();

因此,如果您希望它可见超过3秒,那么只需花费您想要的时间并将其乘以1000,因为Interval是以毫秒为单位。

答案 1 :(得分:1)

当然你可以使用Thread.Sleep

lblWarning.Text = "This action is for administrator only.";
System.Threading.Thread.Sleep(5000);
lblWarning.Hide();

其中5000 =您要暂停/等待/睡眠的毫秒数

答案 2 :(得分:0)

以下解决方案适用于wpf应用程序。当您启动计时器时,将启动一个单独的线程。要从该线程更新UI,您必须使用调度方法。请阅读代码中的注释并相应地使用代码。必填标头

  

使用System.Timers;

private void DisplayWarning(String message, int Interval = 3000)
    {
        Timer timer = new Timer();
        timer.Interval = Interval;
        lblWarning.Dispatcher.Invoke(new Action(() => lblWarning.Content = message));
        lblWarning.Dispatcher.Invoke(new Action(() => lblWarning.Visibility = Visibility.Visible));

        // above two line sets the visibility and shows the message and interval elapses hide the visibility of the label. Elapsed will we called after Start() method.

        timer.Elapsed += (s, en) => {
            lblWarning.Dispatcher.Invoke(new Action(() => lblWarning.Visibility = Visibility.Hidden));
            timer.Stop(); // Stop the timer(otherwise keeps on calling)
        };
        timer.Start(); // Starts the timer. 
    }

用法:

DisplayWarning("Warning message"); // from your code

答案 3 :(得分:0)

如果您在2020年使用UWP XAML并且msgSaved标签是TextBlock,则可以使用以下代码:

seq

答案 4 :(得分:0)

此功能在标签上显示特定时间段的特定信息,包括文本样式

public void show_MSG(string msg, Color color, int d)
    {
        this.Label.Visible = true;
        this.Label.Text = msg;
        this.Label.ForeColor = color;
        Timer timer = new Timer();
        timer.Interval = d;
        timer.Tick += (object sender, EventArgs e) =>
        {
            this.Label.Visible = false;
        }; timer.Start();
    
    }
相关问题