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);
}
}