Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I add support for scrolling in a custom 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 acces 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 ) 
  { 
    bottom = rect.Bottom; 
    left = rect.Left; 
    right = rect.Right; 
    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 rect = new RECT( ClientRectangle ); 
  ScrollWindow( Handle, 0, yAmount, ref rect, ref rect ); 
}

Contributed from George Shepherd's Windows Forms FAQ