I have a panel (Windows Forms) and I want to disable a panels horizontal scrollbar. I tried this:
HorizontalScroll.Enabled = false;
But tha
Try to implement this way, it will work 100%
panel.HorizontalScroll.Maximum = 0;
panel.AutoScroll = false;
panel.VerticalScroll.Visible = false;
panel.AutoScroll = true;
Managed C++ code to hide HScroll Bar:
// Hide horizontal scroll bar
HWND h = static_cast<HWND> (this->Handle.ToPointer());
ShowScrollBar(h, SB_HORZ, false);
SuperOli´s answer was great!
I updated the code so it is possible to close the form without any error.
I hope it works for you as well.
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowScrollBar(IntPtr hWnd, int wBar, bool bShow);
private enum ScrollBarDirection
{
SB_HORZ = 0,
SB_VERT = 1,
SB_CTL = 2,
SB_BOTH = 3
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == 0x85) // WM_NCPAINT
{
ShowScrollBar(panel1.Handle, (int)ScrollBarDirection.SB_BOTH, false);
}
base.WndProc(ref m);
}
I was having this same type of issue with the horizontal scroll appearing when AutoScroll=true, it only showed up when the vertical scrollbar appeared. I finally figured out that I removed padding from the panel and by adding 20 back to the right padding it allowed the vertical scrollbar to appear and not show the horizontal one.
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;
}
}