通过单击按钮更改文本标签和颜色

时间:2013-10-20 14:42:10

标签: vb.net visual-studio-2010 visual-studio colors

我有这个问题,我想点击程序中的按钮时设置这样的计时器:

第一个文字标签"Not Connected"颜色红色)更改为"Verifying"颜色绿色),一段时间后它会永久性地更改为{ {1}}(颜色绿色

我该怎么做?

2 个答案:

答案 0 :(得分:0)

由于您没有提供带有计时器的代码来了解您想要做什么我无法给出更好的答案,您可以调整我执行的代码:

Public Class Form1

Private Enum State
    NotConnected = 141 ' Red
    Verifying = 53 ' DarkGreen
    Connected = 79 ' Green
End Enum

Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click

    Select Case Label1.Tag

        Case Nothing
            SetLabelState(Label1, "Not Connected ", State.NotConnected)

        Case State.NotConnected
            SetLabelState(Label1, "Verifying", State.Verifying)

        Case State.Verifying
            SetLabelState(Label1, "Connected", State.Connected)

        Case State.Connected
            ' Do nothing here

        Case Else
            Throw New Exception("Select case is out of index")

    End Select

End Sub

Private Sub SetLabelState(ByVal lbl As Label, _
                          ByVal txt As String, _
                          ByVal col As State)

    lbl.BackColor = Color.FromKnownColor(CType(col, KnownColor))
    lbl.Tag = col
    lbl.Text = txt

End Sub

End Class

答案 1 :(得分:0)

您可以在此处使用Timer类。 这是我在代码中实现的->

    //click event on the button to change the color of the label
    public void buttonColor_Click(object sender, EventArgs e)
            {
                Timer timer = new Timer();
                timer.Interval = 500;// Timer with 500 milliseconds
                timer.Enabled = false;

                timer.Start();

                timer.Tick += new EventHandler(timer_Tick);
            }

           void timer_Tick(object sender, EventArgs e)
        {
            //label text changes from 'Not Connected' to 'Verifying'
            if (labelFirst.BackColor == Color.Red)
            {
                labelFirst.BackColor = Color.Green;
                labelFirst.Text = "Verifying";
            }

            //label text changes from 'Verifying' to 'Connected'
            else if (labelFirst.BackColor == Color.Green)
            {
                labelFirst.BackColor = Color.Green;
                labelFirst.Text = "Connected";
            }

            //initial Condition (will execute)
            else
            {
                labelFirst.BackColor = Color.Red;
                labelFirst.Text = "Not Connected";
            }
        }