10

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;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BigBug
  • 6,202
  • 23
  • 87
  • 138

4 Answers4

17

For Getting the size of a Windows Form:

int formHeight = this.Height;
int formWidth = this.Width;
T30
  • 11,422
  • 7
  • 53
  • 57
12
    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
}
imre Boersma
  • 71
  • 1
  • 9
Damith
  • 62,401
  • 13
  • 102
  • 153
4

You want to set Dock = DockStyle.Fill to dock the control to fill its parent.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
3

Set it to ClientRectangle.Width.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Hmmm I added an edit at the end of my code - is this what you meant i should try? If not please provide an example. – BigBug Oct 30 '11 at 02:30
  • Did you read what you just wrote? `X` means the location, not the size. – SLaks Oct 30 '11 at 02:37