Search code examples
c#winformspanelsmooth-scrolling

Smooth drawing or painting of child controls in Panel while scrolling


While using Panel control in TabPage of Tab control, I have quite a few child controls like RichTextBox, Buttons, Labels etc.

Problem is when I scroll in the Panel, there is a flickering inside. The child controls are not being shown/drown/painted smoothly like they are already there.

Looking for something that could make this scrolling smooth and remove the flickering effect. Any suggestions would help a lot. I tried a several other methods like DoubleBuffered, but didn't really work.


Solution

  • Well I solved the problem with combination of different other suggestions, below is the code that removed flickering for me, essentially making it DoubleBuffered using Win API.

    References here and here.

    public partial class SmoothScrollPanel : UserControl
    {
        public SmoothScrollPanel()
        {
            InitializeComponent();
            // this.DoubleBuffered = true;
        }
    
        private const int WM_HSCROLL = 0x114;
        private const int WM_VSCROLL = 0x115;
    
        protected override void WndProc(ref Message m)
        {
            if ((m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL)
            && (((int)m.WParam & 0xFFFF) == 5))
            {
                // Change SB_THUMBTRACK to SB_THUMBPOSITION
                m.WParam = (IntPtr)(((int)m.WParam & ~0xFFFF) | 4);
            }
            base.WndProc(ref m);
        }
    
        protected override CreateParams CreateParams
        {
            get
            {
                var cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;    // Turn on WS_EX_COMPOSITED
                return cp;
            }
        }
    }