Apply new colour (with Gradient) to Win Forms button onClick

后端 未结 2 1039
长情又很酷
长情又很酷 2021-01-16 08:01

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

相关标签:
2条回答
  • 2021-01-16 08:18

    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

    0 讨论(0)
  • 2021-01-16 08:29

    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.

    0 讨论(0)
提交回复
热议问题