问题描述
||
我想获得一个winforms窗体的height和width属性,以便能够对所有窗体进行着色吗?
我已经尝试过此代码。
private void Form1_Load(object sender,EventArgs e)
{
using (Graphics g = this.CreateGraphics())
{
Rectangle r=this.DisplayRectangle;
g.DrawRectangle(Pens.Black,new Rectangle(0,r.X,r.Y));
}
}
但这并不能完成任务。如何使用图形对象和矩形对象将整个表单涂成黑色?
解决方法
如果您这样做的话,您将只在窗口所在的屏幕上绘画。该窗口不知道这一点,并且由于任何原因更新该窗口时,它将重新绘制而没有颜色。
使用
Paint
事件在窗口上绘制图形。为该事件添加一个事件处理程序,每当需要重绘窗口时都会调用该事件处理程序。事件参数包含一个应用于绘图的“ 2”对象。
使用DisplayRectangle
的Width
和Height
属性作为宽度和高度,而不是X
和Y
属性。但是,由于将“ 2”对象剪切到要更新的区域,因此您可以使用“ 9”方法将其填充颜色。
,我的表单上有两个按钮(在设计视图中)button1_Click
将其涂成黑色,button2_Click
将窗体涂成控制颜色。
public partial class Form2 : Form
{
private Brush brushToPaint;
public Form2()
{
InitializeComponent();
brushToPaint = SystemBrushes.Control;
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.FillRectangle(brushToPaint,this.DisplayRectangle);
}
private void button1_Click(object sender,EventArgs e)
{
brushToPaint = Brushes.Black;
InvokePaint(this,new PaintEventArgs(this.CreateGraphics(),this.DisplayRectangle));
}
private void button2_Click(object sender,EventArgs e)
{
brushToPaint = SystemBrushes.Control;
InvokePaint(this,this.DisplayRectangle));
}
}
,您是否必须使用Graphics
和DisplayRectangle
执行此操作?
表单具有称为BackColor的属性,您可以将其简单地设置为black:
private void Form1_Load(object sender,EventArgs e)
{
this.BackColor = Color.Black;
}