Mega Code Archive

 
Categories / Delphi / Examples
 

Adjusting form size to accommodate a required client size

Question: How do I adjust my form size to accommodate a required client size? Answer: You can make a call to the Windows API function AdjustWindowRectEx(). This function takes in a rectangle of your requested client size in screen space, and returns a rectangle containing the required window size and position to accommodate the request. Notes: 1) The returned rectangle may be larger than the screen. 2) The form's client area may be reduced by the automatic addition of scroll bars. 3) Windows containing title bars have a minimum size allowed by the system, and cannot be made smaller. 4) Menus may form multiple menu bars if the Window is sized too small for the menu to display on a single line. The AdjustWindowRect() function does not take this into account. Example: procedure TForm1.Button1Click(Sender: TObject); var pt : TPoint; r : TRect; begin pt := ClientToScreen(Point(0, 0)); r.Left := pt.x; r.Top := pt.y; pt := ClientToScreen(Point(128, 128)); r.Right := pt.x; r.Bottom := pt.y; AdjustWindowRectEx(r, GetWindowLong(Form1.Handle, GWL_STYLE), Form1.Menu = nil, {if Form1 has a menu} GetWindowLong(Form1.Handle, GWL_EXSTYLE)); Form1.Top := r.Top; Form1.Left := r.Left; Form1.Width := r.Right - r.Left; Form1.Height := r.Bottom - r.Top; end;