2012-07-05 51 views
1

我遇到了几种将渐变样式应用于Windows窗体应用程序中的对象的方法。所有的方法都涉及覆盖OnPaint方法。但是,我正在根据验证在运行时查看更改风格。应用新颜色(使用渐变)获取窗体按钮onClick

如何将新渐变样式应用于已经呈现的按钮(就像我可以使用BackColor一样)?

R, C.

UPDATE:这是我目前正在使用的代码。这似乎没有任何效果

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

被称为由

btn.Paint += new PaintEventHandler(this.Button_Paint); 

进一步更新当前代码

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

回答

3

这有两个部分。其一,正如SLaks所说,你需要在你的Paint事件处理程序中绘制梯度。这将是这个样子(我在这里的例子是有点乱为简洁起见):

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

此外,你需要做您的验证和重绘按钮被点击时:

btn.Click += Button_Click; 

...

private void Button_Click(object sender, EventArgs e) 
{ 
    DoValidations(); 
    btn.Invalidate(); 
} 

当然,你必须执行DoValidations()MyFormIsValid()方法。

这里的整个事情作为一个可运行示例程序:http://pastebin.com/cfXvtVwT

+0

谢谢,但我仍然没有发生任何事情。通过我的代码,我可以确认两行(添加新的PaintEventHandler并调用Invalidate())正在被击中。但是,函数Button_Paint没有被调用。我甚至在按钮上添加了一个Refresh(),没有任何改变。 – 2012-07-05 14:04:15

+0

奇怪...我有这个作为示例应用程序运行...我会发布整个事情。 – andypaxo 2012-07-05 14:11:21

+0

谢谢。我将用我正在运行的代码更新我的问题。 – 2012-07-05 14:15:28

2

正如你所看到的,你需要处理Paint事件。

您可以在类中设置布尔值来指示是否绘制渐变。

+0

+1,你能告诉我们的代码?或[SO]引用 – 2012-07-05 11:31:41

+0

我将包含用于覆盖表单(在渲染)很快的代码。我仍然不确定如何用类似的方法重载按钮Paint事件。 – 2012-07-05 11:34:06