Tuesday, September 1, 2009

Custom Drawn Scrollbar

Introduction

I was working (in my free time) on a calendar control which looks similar to the one in Outlook 2007 and I encountered, among other problems, that the standard scrollbar doesn't fit nicely with the look of my calendar control. So I searched the Web and CodeProject for custom drawn scrollbars.

Among others, I found the article from Greg Ellis. Although it pointed me in the right direction, I missed some things the system scrollbar is capable of. As a last resort, I searched in the help of Visual Studio and found a simple example of a custom drawn scrollbar which I took as a starting point.

Some Remarks

This control is mostly useful for developers who build their own custom drawn controls and need a scrollbar.

The scrollbar has one major shortcoming - the width is fixed. I didn't need this feature and the drawing would be more complex, so I left it out.
Because I used collection initializers, the project builds only with a C# 3.0 compiler and upwards, but that can easily be fixed.
To enable the scrollbar to scroll when pressing and holding the mouse button, I used a timer - didn't find another way.
The drawing is realized with GDI+ (in a separate renderer class) with two exceptions: the little arrow in the arrow buttons and the grip in the thumb are images - there, shame on me, I was a bit lazy.

Layout of the Control

As it is said, a picture says more than thousand words, here is a diagram with the essential classes:

Please note that the property Opacity sets the opacity of the context menu, not of the control itself.
I left out the control designer class because it's not really necessary, only when using Visual Studio.

Let's Start

When drawing a control from scratch, it's necessary to override the OnPaint method and also, in my humble opinion, to set some control styles in the constructor:


See full detail: http://www.codeproject.com/KB/miscctrl/customdrawnscrollbar.aspx

No comments: