GroupBox autosize - c#

Take a GroupBox, put let say Label inside and then set AutoSizeMode = GrowAndShrink and AutoSize = true.
Two problems will arise:
There is a huge gap between Label and bottom of GroupBox (almost enough to fit another Label lol);
AutoSize doesn't respect the GroupBox.Text property.
Question is how to make GroupBox.AutoSize working properly? Properly means: minimum Width should be enough to fit GroupBox.Text, there should be no gaps below for unknown reason (it's not Margin, nor Padding and it looks pretty ugly).
I've tried to measure string length in OnPaint and setting MinimumSize right there. It works, but I have doubts about this, as if I would want to actually set MinimumSize later - it will be lost after repaint.
Update, here is screenshot:

You can get rid of the unwanted yellow space at the bottom by deriving a new class from GroupBox that adjusts the bottom edge a bit. In VB something like ...
Public Class BetterGroupBox
Inherits GroupBox
Public Overrides Function GetPreferredSize(ByVal proposedSize As Size) As Size
Dim ns = MyBase.GetPreferredSize(proposedSize)
Return New Size(ns.Width, ns.Height - 15)
End Function
End Class

It's simple that the location of your Label is fixed at some point other than (0,0), try this:
label1.Location = Point.Empty;
You may also want to try setting the Padding of your GroupBox to 0 for all (default is 3):
groupBox1.Padding = new Padding(0);

It seems as though the GroupBox control has a predefined padding of sorts when growing the control if AutoSize = true. That is, once a control (inside the GroupBox) gets within 20 pixels or so of the bottom of the GroupBox, the GroupBox starts growing. This causes a 20 pixel or so padding from the bottom of the bottom-most control to the bottom of the GroupBox (as highlighted in yellow by #Sinatr's attached image).
Based on my observations, the padding seems to be less when growing the Width of the GroupBox.
At any rate, you can do something like the following "get around" the issue:
public void MyFunction()
{
groupBox1.AutoSize = true;
// Do stuff (e.g., add controls to GroupBox)...
// Once all controls have been added to the GroupBox...
groupBox1.AutoSize = false;
// Add optional padding here if desired.
groupBox1.Height = myBottomMostControl.Bottom;
}

Related

Sizing form to Control.Bounds.Bottom creates unexpected result

I have a windows form, in which I have a Tab Control in which I have other controls.
Since the amount of controls is dynamic and I want to size the Form just right I have this piece of code:
int w = 0;
int h = 0;
foreach (Control x in Tab_Control.Controls)
{
if (x.Bounds.Right > w) w = x.Bounds.Right;
if (x.Bounds.Bottom > h) h = x.Bounds.Bottom;
}
Tab_Control.Size = new Size(w, h);
Form1.Size = new Size(w, h);
While this sets the form width just right its height crops two controls on the bottom. I thought it might be because the positions are relative to the parent control, but when I used "PointToScreen(Point.Empty)" to get some real coordinates I found the difference to be 21 pixels, which didn't help much.
So I am wondering why setting the form height to h ends up being too short.
The discrepancy is due to the size of the form's title bar.
You are calculating the size required by the controls correctly, but you are then setting the overall size of the window - which includes the title bar - to that height.
You'll need to add on the height of the title bar to the size you are calculating.
You can get the height of the title bar from the CaptionHeight property in System.Windows.Forms.SystemInformation
If that doesn't cover all of the discrepancy then look at the form's border thickness to see if you need to take that into account as well
Simply set the ClientSize property instead.
Better yet is to write no code at all. Set the form's AutoSize property to True, AutoSizeMode to GrowAndShrink. You surely prefer setting the Margin property on control(s) at the bottom and the right so there's a decent space between the control and the border.

SplitContainer Panel Resize Issue

The General Problem
The application is C# WinForms .Net 4.0.
I have a SplitContainer that takes up most of the form, it is set to Anchor in all directions so it re-sizes along with the form. The left panel (Panel1) has a simple menu, no problems here. The right panel (Panel2) is more complex and contains a number of nested tab controls (with lots of controls) - it is painfully complex, but it's not changing.
The problem is that re-sizing the form doesn't work so well. In fact, if you resize by dragging the edges slowly then it works ok, but drag quickly or use the "restore" button (top-right of form) then the issue occurs.
My Control Hierarchy
The following is a simple example of my control hierarchy, its definitely a cut down version but does highlight the nested tab control which may help with replication:
Form
Split Container (anchor: top, left, bottom, right)
SC Panel1 (min width: 300)
TreeViewControl (forget what it is called)
SC Panel2
Panel (anchor: top, left, bottom, right)
Tab Control (anchor: top, left, bottom, right)
Tab Control w/ lots of pages that overflow screen and require the navigation buttons to show in top right corner (anchor: top, left, bottom, right)
Debug Details
After some debugging it appears that it is in fact Panel2 (a child of the split container) that doesn't resize properly, and the actual SplitContainer itself resizes fine.
Here are the debug values that show this...
Full width form, before resize:
splitContainerMain.Width: 1479
splitContainerMain.Panel2.Width: 1206
panelCenter.Width: 1203
tabControlMain.Width: 1215
All as expected, splitContainerMain.Panel2.Width is smaller than splitContainerMain.Width.
After resize where the issue occurs:
splitContainerMain.Width: 815
splitContainerMain.Panel2.Width: 1206
panelCenter.Width: 1203
tabControlMain.Width: 1215
As can be seen, the splitContainerMain.Width has resized as desired, but the splitContainerMain.Panel2.Width and subsequently its children have not.
NOTE: Please remember, the width updates correctly if I manually resize the form slowly - this is not a problem with me not correctly setting any anchors.
My Efforts So Far
What I have tried to do is use various Form resize events and try to set the widths manually, but to no avail. I think what I would like to try is to set the Panel2.Width value from within an event of some sort.
What I Am Looking For
Is there anyway to force splitContainerMain.Panel2.Width to resize correctly when the splitContainerMain size changes?
Alternatively, how can I calculate what the Panel2.Width should be? And how can I set that value from the Form.Resize event? (or another event?)
Though the question is about 6 years old, I opted to answer this because I was in the same situation as the opening post. Unfortunately, the orientation was not specified. So, my answer would address the ones with Horizontal orientation.
Please translate to C# as this code is in VB.
Private Sub splitContainerMain_Resize(sender As Object, e As EventArgs) Handles splitContainerMain.Resize
'/* This is a work around about panels being left out when SplitContainer is resized */
Dim pnl1Height As Single = splitContainerMain.SplitterDistance '/* Get upper panel height */
Dim pnl2Height As Single = splitContainerMain.Height - splitContainerMain.SplitterDistance '/* Get lower panel height */
splitContainerMain.Panel1.SetBounds(0, 0, splitContainerMain.Width, pnl1Height) '/* Set Upper panel bounds */
'/* Set lower panel bounds, with a top of upper panel height plus splitter width */
splitContainerMain.Panel2.SetBounds(0, pnl1Height + splitContainerMain.SplitterWidth, splitContainerMain.Width, pnl2Height)
End Sub
From what I see u should set anchor to none for controls that are creating problem including splitcontainer pannels.
Also I would suggest to use dock fill property to best use the splitcontainers.
If need further help please provide designer file so can have a better look.
So on each Change event you are creating a new thread, that thread will then wait 100 ms and then do the recize??? thats stupid. You can have a thread created at the constructor, then calling Start() on your thread which could have the following:
private void resizeMe()
{
this.BeginInvoke((Action)() => {
splitContainer.Height = tableBorder.Height;
splitContainer.Width = tableBorder.Width;
}
}
Exactly the same problem, below code worked for me:
Surround splitContainer in a panel "tableBorder"
On tableBorder
Dock = DockStyle.Fill;
On split Container, (no anchoring)
Dock = DockStyle.None;
On tableBorder SizeChanged event
private void tableBorder_SizeChanged(object sender, EventArgs e)
{
new Thread(() => { resizeMe(); }).Start();
}
private void resizeMe()
{
Thread.Sleep(100);
this.BeginInvoke((Action)(() => {
doIt();
}));
}
private void doIt()
{
splitContainer.Height = tableBorder.Height;
splitContainer.Width = tableBorder.Width;
}
There is a small lag, but works

Panel with fixed size

I have a homework, where I need to create a winforms game using C#. I have the following components:
Panel subclass with custom paint event
Panel with default windows UI elements.
I want them to arrange like this:
Because I draw on the center panel manually, I want to set it's Width, and Height fixed, so the Form subclass, what will contain it, would show the whole panel.
I tried setting the size manually in the panel subclass:
Width = someFixedWidth;
Height = someFixedHeight;
Then adding it to the containing Form:
GamePanel panel = new GamePanel(...);
panel.Dock = DockStyle.Center;
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.Controlls.Add(panel);
Using this, I thought, that the form will respect the size of the Panel, but it just shrinks the window to so small, that nothing is visible, only the title.
So my question is, how would I be able to set the size of the GamePanel manually, and then dock it in the center of the form, so that the Form will respect the size I set, and doesn't makes it smaller/bigger?
The Dock property is used to define the behavior of the component during resizing Container (Form) The way you did the screen is not centralized but is resized according to the screen changes, the ideal is to use a method to reposition the control and set its size. See this:
SuspendLayout();
Width = someFixedWidth;
Height = someFixedHeight;
panel.Size = new Size(panelWidth, panelHeight);
panel.Location = new Point( ClientSize.Width / 2 - panelWidth / 2, ClientSize.Height / 2 - panelHeight / 2);
panel.Anchor = AnchorStyles.None;
panel.Dock = DockStyle.None;
ResumeLayout();
In my case, I edited minimum height/width of the panel and it worked.
I tried to edit the code which related to design but it was not recommended to rewrite auto-generated code.
Thank you.

How to resize a button depending on its text

In the process of translating an application with C# + Winforms, I need to change a button's text depending on the language.
My problem is the following :
Let's say I want to translate a button from "Hi all!" to "Bonjour tout le monde" !
As you can guess, the button's size won't be the same if I enter english text or french one... My question is "simple", how can I manage to resize the button on the fly so the text fits its content in the button ?
So far I got something like that !
[Hi all!]
[Bonjour]
There's absolutely no need to use the underlying Graphics object as the other posters have said.
If you set the button's AutoSize property to true, the AutoSizeMode to GrowAndShrink, and the AutoEllipsis to false, it will resize automatically to fit the text.
That being said, you may need to make several layout adjustments to make this change fit into your UI. You can adjust the button's padding to add space around the text, and you may want to place your buttons in a TableLayoutPanel (or something) to stop them from overlapping when they resize.
Edit:
#mastro pointed out that: AutoEllipsis is only valid when AutoSize is false (As explained in the documentation), so it can be safely ignored as long as the other three properties are set correctly.
Your best bet is to set the AutoSize property as described ach's answer
However if AutoSize isn't working for you, resizing the button in code is easy enough. You can just need to set the button's width. The trick is making it big enough to fit your text.
using(Graphics cg = this.CreateGraphics())
{
SizeF size = cg.MeasureString("Please excuse my dear aunt sally",this.button1.Font);
// size.Width+= 3; //add some padding .net v1.1 and 1.0 only
this.button1.Padding = 3;
this.button1.Width = (int)size.Width;
this.button1.Text = "Please excuse my dear aunt sally";
}
Try this:
Button.AutoSize = true;
Button.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowOnly;
Button.TextAlign = ContentAlignment.MiddleLeft;
Button.Padding = new Padding(0, 0, 0, 0);
To enable a Button in WinForms grow and/or shrink depending on the size of the Text, you need to set the button's AutoSize property to True and the AutoSizeMode property to GrowAndShrink.
// C#
btn.AutoSize = true;
btn.AutoSizeMode = AutoSizeMode.GrowAndShrink;
' VB.NET
btn.AutoSize = True
btn.AutoSizeMode = AutoSizeMode.GrowAndShrink
Please note that the AutoSize property will only allow the button's size to grow if the AutoSizeMode property is set to GrowOnly; by changing the AutoSizeMode property to GrowAndShrink, the button will now automatically extend or reduce in width and height based on its Text property.
Also note that in setting the two properties as shown above, you can make use of new lines (Environment.NewLine or vbCrLf) in the Text property and the button will scale down as needed.
As Andrew Hanlon explains, you can set AutoSize = true.
When doing so, you can also attain a perfect layout of the buttons automatically by placing them on a FlowLayoutPanel.
The horizontal distance between them will always stay the same when the FlowDirection of the FlowLayoutPanel is LeftToRight or RightToLeft. You can adjust this distance by setting the Margin property of the buttons appropriately. You can create groups of buttons by increasing the left margin of buttons beginning a new group.
If you set the Dock property of the buttons to DockStyle.Fill, they will even grow their width automatically in order to fit to the widest button if the FlowDirection of the FlowLayoutPanel is TopDown or BottomUp.
btn.AutoSizeMode = AutoSizeMode.GrowOnly;
btn.AutoSize = true;
btn.Dock = DockStyle.Fill;
In addition to setting the AutoSize to true and the AutoSizeModeto GrowAndShrink, as suggested in the other answers, you may also need to set the TextImageRelation property, if you have set the button image, so that the text doesn't overlap the image.

DomainUpDown (spinner) control is cutting off the bottom pixel of displayed text

I'm using winforms and the DomainUpDown control's height is locked at 20 pixels, which results in "y"'s and other characters with descenders cut off on the bottom.
My initial thought about how to fix the problem was to change the controls height, but I couldn't do so. In the designer I only have controls to drag it's size by width. The property page immediately reverts any change to height I make. Attempts to change the value in code silently fail; no error, no exception, but no change to the value either.
In this sample form the "g" in the DomainUpDown will be cut.
public partial class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DomainUpDown domainUpDown1 = new System.Windows.Forms.DomainUpDown();
public Form1()
{
this.domainUpDown1.Location = new System.Drawing.Point(16, 8);
this.domainUpDown1.Size = new System.Drawing.Size(212, 20);
this.domainUpDown1.Text = "why are descenders like g cut?";
this.ClientSize = new System.Drawing.Size(328, 64);
this.Controls.Add(this.domainUpDown1);
}
}
I see the same fixed height behaviour when using DomainUpDown controls. You can adjust the size of the font that is used, which changes the height of the control to match the text. Perhaps adjusting the size of your text slightly can help with the clipping of the characters with "descenders". I see no clipping using the default 8.25pt font.
EDIT:
After replicating on XP running the classic theme and with Dan's testing, the problem appears to be the thickness of the borders and padding, which cut off the g.
Setting the BorderStyle to either FixedSingle or None fixes the problem.
domainUpDown1.BorderStyle = BorderStyle.FixedSingle;
or
domainUpDown1.BorderStyle = BorderStyle.None;
You will need to see what looks best in your application. Oh, and setting your theme to XP (rather than classic) will work too.

Categories

Resources