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 looking the change the style at runtime based on validation.
How can I apply the new gradient style to an already rendered button (like I can with BackColor)?
R,
C.
UPDATE: This is the code I am currently using. It appears to have no effect
private void Button_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
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);
this.btn.Invalidate();
}
Being called by
btn.Paint += new PaintEventHandler(this.Button_Paint);
FURTHER UPDATE WITH CURRENT CODE
private void Button_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
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);
}
private void btn_Click(object sender, EventArgs e)
{
btn.Paint += new PaintEventHandler(this.Button_Paint);();
btn.Invalidate();
}
There are two parts to this. One, as SLaks said, you need to draw the gradient in your
Paintevent handler. This would look something like this (my example here is a bit messy for the sake of brevity):Also, you need to do your validation and redraw the button when it is clicked:
…
Of course, you’ll have to implement the
DoValidations()andMyFormIsValid()methods.Here’s the whole thing as a runnable sample program: http://pastebin.com/cfXvtVwT