How do I disable the horizontal scrollbar in a Panel

前端 未结 11 1924
别那么骄傲
别那么骄傲 2020-12-01 12:13

I have a panel (Windows Forms) and I want to disable a panels horizontal scrollbar. I tried this:

HorizontalScroll.Enabled = false;

But tha

11条回答
  •  生来不讨喜
    2020-12-01 12:59

    I was looking for an answer to the question how to add a scrollbar to a box when needed and remove it when not needed. This is the solution i came up with for a textbox, with maximum allowed width and height, resized for the text displayed.

    private void txtOutput_TextChanged(object sender, EventArgs e)
        {
            // Set the scrollbars to none. If the content fits within textbox maximum size no scrollbars are needed. 
            txtOutput.ScrollBars = ScrollBars.None;
    
            // Calculate the width and height the text will need to fit inside the box
            Size size = TextRenderer.MeasureText(txtOutput.Text, txtOutput.Font);
    
            // Size the box accordingly (adding a bit of extra margin cause i like it that way)
            txtOutput.Width = size.Width + 20;
            txtOutput.Height = size.Height + 30;
    
    
            // If the box would need to be larger than maximum size we need scrollbars
    
            // If height needed exceeds maximum add vertical scrollbar
            if (size.Height > txtOutput.MaximumSize.Height)
            {
    
                txtOutput.ScrollBars = ScrollBars.Vertical;
    
                // If it also exceeds maximum width add both scrollbars 
                // (You can't add vertical first and then horizontal if you wan't both. You would end up with just the horizontal) 
                if (size.Width > txtOutput.MaximumSize.Width)
                {
                    txtOutput.ScrollBars = ScrollBars.Both;
                }
            }
    
            // If width needed exceeds maximum add horosontal scrollbar 
            else if (size.Width > txtOutput.MaximumSize.Width)
            {
                txtOutput.ScrollBars = ScrollBars.Horizontal;
            }
        }
    

提交回复
热议问题