Custom Layout


Yes, even with all the layout support that exists in VS05, the Windows Forms Designer, and the .NET Framework, you may still encounter situations that are complex enough to make it difficult or impossible to use it. It's at times like these that you need to roll up your sleeves, dive down into code, and take advantage of the Layout event, which is fired whenever a control or form needs to reposition its child controlsthat is, when controls are added and removed, or the form is resized.

The following Layout event handler re-creates the tabular layout from Figure 4.45 by programmatically arranging the nine button controls proportionally as the form is resized:

Button[] buttons =   new Button[] {     this.button1, this.button2, this.button3,     this.button4, this.button5, this.button6,     this.button7, this.button8, this.button9 }; ... void LayoutEventForm_Layout(object sender, LayoutEventArgs e) {   // Arrange the buttons in a grid on the form   int cx = this.ClientRectangle.Width / 3;   int cy = this.ClientRectangle.Height / 3;   for( int row = 0; row != 3; ++row ) {     for( int col = 0; col != 3; ++col ) {       Button button = buttons[col * 3 + row];       button.SetBounds(cx * row, cy * col, cx, cy);     }   }   // Set form client size to be multiple of width/height   this.SetClientSizeCore(cx * 3, cy * 3); }


Although you can use the Layout event to handle all the layout needs of a form, it's much easier to use anchoring, docking, and grouping and fall back on the Layout event only to handle special cases. One advantage of handling the Layout event, however, is that it is protected by SuspendLayout and ResumeLayout, whereas the Resize event is not.[7]

[7] See http://blogs.msdn.com/jfoscoding/archive/2005/03/04/385625.aspx (http://tinysells.com/12) for more information.




Windows Forms 2.0 Programming
Windows Forms 2.0 Programming (Microsoft .NET Development Series)
ISBN: 0321267966
EAN: 2147483647
Year: 2006
Pages: 216

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net