Live Chat Icon For mobile
Live Chat Icon

WinForms FAQ - Scrolling

Find answers for the most frequently asked questions
Expand All Collapse All

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);
}
Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.