自定義控件的滾動條一直不願意弄,今晚細看了UserControl的繼承結構,感覺是利用ScrollableControl控件實現的,於想查了該基類的使用方法。MSDN中的說明我不得要領,還好在CodeProject找到了一個教程
主題是:Creating a scrollable and zoomable image viewer in C# ,有4個部分組成
- Part 1: The image viewer
- Part 2: Auto scrolling
- Part 3: Panning and keyboard support
- Part 4: Zooming, auto center, size to fit and more!
如果你也只是關心如何在自定義控件實現自動滾動條,可以只看第二部分。
http://www.codeproject.com/Articles/320059/Creating-a-scrollable-and-zoomable-image-viewer-in
其實主要工作只有以下2步。
1.將整個實際需要繪制的區域(有可能超出控件的大小)告訴控件
this.AutoScrollMinSize = new Size(width, height);
2.控件繪件時,需要按自動滾動的位置( this.AutoScrollPosition)調整繪制的開始位置
protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); int x = 20 + this.AutoScrollPosition.X; int y = 20 + this.AutoScrollPosition.Y; this.doc.DrawContent(0, new System.Drawing.Point(x, y), e); }