问题
I'm creating a Windows Forms application. How do I capture the size of the windows form?
Currently I have something that looks like this in my code:
PictureBox display = new PictureBox();
display.Width = 360;
display.Height = 290;
this.Controls.Add(display);
display.Image = bmp;
However, the size of my display is hard-coded to a specific value.
I know that if I want to draw a square that re-sizes I can use something like this:
private Rectangle PlotArea;
private int offset = 30;
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
//// Calculate the location and size of the plot area
//// within which we want to draw the graphics:
Rectangle ChartArea = ClientRectangle;
PlotArea = new Rectangle(ChartArea.Location, ChartArea.Size);
PlotArea.Inflate(-offset, -offset);
Draw PlotArea:
g.DrawRectangle(Pens.Black, PlotArea);
}
Is there a way for me to use method one and grab the size of the form for Height and Width?
I've tried the following code, but it doesn't work...
PictureBox display = new PictureBox();
display.Width = ClientRectangle.Y;
display.Height = ClientRectangle.X;
this.Controls.Add(display);
display.Image = bmp;
回答1:
PictureBox display = new PictureBox();
display.Width = ClientRectangle.Width;
display.Height = ClientRectangle.Height;
this.Controls.Add(display);
display.Image = bmp;
When you resize the window:
private void Form1_Resize(object sender, System.EventArgs e)
{
Control control = (Control)sender;
// set the PictureBox width and heigh here using control.Size.Height
// and control.Size.Width
}
回答2:
For Getting the size of a Windows Form:
int formHeight = this.Height;
int formWidth = this.Width;
回答3:
You want to set Dock = DockStyle.Fill
to dock the control to fill its parent.
回答4:
Set it to ClientRectangle.Width
.
来源:https://stackoverflow.com/questions/7942939/getting-the-size-of-a-windows-form