Reputation: 2000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace painter
{
public partial class Form1 : Form
{
Array values = Enum.GetValues(typeof(Color));
Random random = new Random();
public bool shouldpaint = false;
public Form1()
{
InitializeComponent();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
shouldpaint = true;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
shouldpaint = false;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (shouldpaint == true)
{
Graphics a = CreateGraphics();
Color randomColor = (Color)values.GetValue(random.Next(values.Length));
a.FillEllipse(new SolidBrush(randomColor), e.X, e.Y, 5, 5);
}
}
}
}
I am trying to randomize SolidBrush(randomColor) so that when I move my mouse, its color will change and painted accordingly. I tried above code, it gave me "An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll" . Can you check my randomization code? Before I added that code it was working as intended according to my predetermined color.
Upvotes: 0
Views: 142
Reputation: 2172
If you want random colors, you have to create random number, into the max a min values allowed by the Color Enum.
I think it's better to forget the color enum, to use the old RGB constructor instead.
Dim oRandomNumbers As New Random
Dim oColor as Color
oColor =Color.FromArgb(255, _
oRandomNumbers.Next(0, 256), _
oRandomNumbers.Next(0, 256), _
oRandomNumbers.Next(0, 256))
In c#:
Random oRandomNumbers = new Random();
Color oColor = default(Color);
oColor = Color.FromArgb(255, oRandomNumbers.Next(0, 256),
oRandomNumbers.Next(0, 256),
oRandomNumbers.Next(0, 256));
Edit: As @Enigmativity says, 256 its the exclusive upper limit, so this will give you random numbers from 0 to 255
Upvotes: 3