I want 开发者_如何学运维to obtain the height and width properties of a winforms form to be able to color all of it?
I've tried this code..
private void Form1_Load(object sender, EventArgs e)
{
using (Graphics g = this.CreateGraphics())
{
Rectangle r=this.DisplayRectangle;
g.DrawRectangle(Pens.Black, new Rectangle(0, 0, r.X, r.Y));
}
}
But it doesn't do the job. How do I color the whole form in black with the graphics object and Rectangle object?
If you do like that, you will just be painting on the screen where the window happens to be. The window is not aware of that, and when the window is updated for any reason it will be redrawn without the color.
Use the Paint
event to draw graphics on the window. Add an event handler for the event, and it will be called whenever the window has to be redrawn. The event arguments contains a Graphics
object that you should use for drawing.
Use the Width
and Height
properties of the DisplayRectangle
as width and height, not the X
and Y
properties. However, as the Graphics
object is clipped to the area that is to be updated, you could just use the Clear
method to fill it with a color.
I have two buttons on my form(in design view) button1_Click
is to paint it black, and button2_Click
is to paint form back to Control color.
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, new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));
}
}
Do you have to do this using Graphics
and DisplayRectangle
?
The form has a property called BackColor, which you could simply set to black:
private void Form1_Load(object sender, EventArgs e)
{
this.BackColor = Color.Black;
}
精彩评论