0

我怎样才能让我lblAnzeige的颜色变成红色、白色、绿色、黄色和蓝色?(因此,当我单击btnGelb文本时lblAnzeige,它会在五种颜色之一中更改其颜色)在我的代码中,它会更改为一种 rgb 颜色,但不会更改为正确的 5 种颜色 :(

private void btnGelb_Click(object sender, EventArgs e)
{
    int summe = 0, z;
    lblAnzeige.Text = " ";
    while (summe <= 0)
    {
        z = r.Next(1, 6);
        summe = summe + z;
    }
    lblAnzeige.Text += colors[summe - 1] + "\n";
    lblAnzeige.ForeColor = Color.FromArgb(Farbe.Next(256), Farbe.Next(256), Farbe.Next(256));
}
4

3 回答 3

3

您可以将颜色存储在列表或数组中,然后从列表中随机选择一种。

static readonly IList<Color> myColors =
        new[] { Color.Red, Color.Blue, Color.Green, Color.White, Color.Yellow };
private void btnGelb_Click(object sender, EventArgs e)
{
    int summe = 0, z;
    lblAnzeige.Text = " ";
    while (summe <= 0)
    {
        z = r.Next(1, 6);
        summe = summe + z;
    }
    lblAnzeige.Text += colors[summe - 1] + "\n";
    lblAnzeige.ForeColor = myColors[Farbe.Next(myColors.Count)];
}
于 2013-10-23T18:04:46.073 回答
2
    Private Function RandomColor() As System.Drawing.Color
        Dim MyAlpha As Integer
        Dim MyRed As Integer
        Dim MyGreen As Integer
        Dim MyBlue As Integer
        Randomize()
        MyAlpha = CInt(Int((254 * Rnd()) + 0))
        Randomize()
        MyRed = CInt(Int((254 * Rnd()) + 0))
        Randomize()
        MyGreen = CInt(Int((254 * Rnd()) + 0))
        Randomize()
        MyBlue = CInt(Int((254 * Rnd()) + 0))
        Return Color.FromArgb(MyAlpha, MyRed, MyGreen, MyBlue)

    End Function

我已经在我的一个 vb 项目中拥有它......你应该不难将它转换为 C#

虽然我更喜欢另一个答案,但这可以以更迂回的方式工作

    private void Random()
    {
        RandomNumber random = new RandomNumber();
        int randomInt = random.RandomInRange(1, 5);
    if (randomInt == 1)
            {
                lblLabel.ForeColor =  System.Drawing.Color.Red;
            }
            else if (randomInt == 2)
            {
                lblLabel.ForeColor =  System.Drawing.Color.Yellow;
            }
    else if(randomInt ==3)
            {
        lblLabel.ForeColor =  System.Drawing.Color.White;
            }
            else if (randomInt == 4)
            {
                lblLabel.ForeColor =  System.Drawing.Color.Blue;
            }
            else if (randomInt == 5)
            {
                lblLabel.ForeColor =  System.Drawing.Color.Green;
            }
    }


class RandomNumber
{
    public int RandomInRange(int l, int u)
    {
        Random generator = new Random();
        return generator.Next(l, u);
    }
}
于 2013-10-23T18:11:00.197 回答
0

使用这个简单的字体颜色技术,可以进一步扩展..

    Random NewRGBColor = new Random();
    LastIssueTxtBox.ForeColor = Color.FromArgb(NewRGBColor.Next(256), NewRGBColor.Next(256), NewRGBColor.Next(256));

斯蒂芬

于 2014-11-22T08:28:39.230 回答