George Shepherd's Windows Forms FAQ
Questions and answers in this FAQ have been collected from newsgroup posts, various mailing lists and the employees of Syncfusion.

17. Windows Forms Scrolling

WinForms FAQ Home
   17.1 How do I add support for custom scrolling to my own user control?
   17.2 Are there any events that get fired when the user scrolls?



17.1 How do I add support for custom scrolling to my own user control?


Windows Forms features a ScrollableControl. This will work in most cases where you know the exact dimensions of your control and scroll by pixel. See the MSDN Documentation for ScrollableControl for discussion how to use this control.

Sometimes you may need more customized scrolling, for example if you implemented a text editor and you want to scroll lines and not pixels.

For more customized scrolling you have to use PInvoke to access the Win32 ScrollWindow method. The following code shows how to enable access to the Win32 ScrollWindow method from your code.


          [StructLayout(LayoutKind.Sequential)]
          public struct RECT
          {
               public int left;
               public int top;
               public int right;
               public int bottom;

               public RECT(Rectangle rect)
               {
                    this.bottom = rect.Bottom;
                    this.left = rect.Left;
                    this.right = rect.Right;
                    this.top = rect.Top;
               }

               public RECT(int left, int top, int right, int bottom)
               {
                    this.bottom = bottom;
                    this.left = left;
                    this.right = right;
                    this.top = top;
               }                    
          }


          [DllImport("user32")]
          public static extern bool ScrollWindow(IntPtr hWnd, int nXAmount, int nYAmount, ref RECT rectScrollRegion, ref RECT rectClip);

void MyScrollFunc(int yAmount)
{
                    RECT r = new RECT(ClientRectangle);
                    ScrollWindow(Handle, 0, yAmount, ref r, ref r);
}



17.2 Are there any events that get fired when the user scrolls?


You could override WndProc and listen for (0x114 WM_HSCROLL) and (0x115 WM_VSCROLL) messages (m.Msg will be set to the above values). These messages should be sent when the user scrolls.

© 2001-2010 Copyright Syncfusion Inc. All rights reserved.  |  Privacy Policy  |  Contact  |  Sitemap