I\'ve come across several methods of applying gradient styles to objects in a windows form application. All the methods involve overriding the OnPaint method. However, I am
There are two parts to this. One, as SLaks said, you need to draw the gradient in your Paint
event handler. This would look something like this (my example here is a bit messy for the sake of brevity):
private void Button_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
if (MyFormIsValid()) {
g.DrawString("This is a diagonal line drawn on the control",
new Font("Arial", 10), System.Drawing.Brushes.Blue, new Point(30, 30));
g.DrawLine(System.Drawing.Pens.Red, btn.Left, btn.Top,
btn.Right, btn.Bottom);
}
else {
g.FillRectangle(
new LinearGradientBrush(PointF.Empty, new PointF(0, btn.Height), Color.White, Color.Red),
new RectangleF(PointF.Empty, btn.Size));
}
}
Also, you need to do your validation and redraw the button when it is clicked:
btn.Click += Button_Click;
...
private void Button_Click(object sender, EventArgs e)
{
DoValidations();
btn.Invalidate();
}
Of course, you'll have to implement the DoValidations()
and MyFormIsValid()
methods.
Here's the whole thing as a runnable sample program: http://pastebin.com/cfXvtVwT
As you've seen, you need to handle the Paint
event.
You can set a boolean in your class to indicate whether to draw the gradient or not.