Table Of Contents
- Introduction
- Minimum Requirements
- Requirements: What I Need
- Requirements: What I Don't Need
- The Prototype Design
- The GUI Components
- The Object Model
- The Prototype Implementation
- The Objects
- OutlookBar
- IconPanel
- Eye Candy
- Conclusion
This is yet another Outlook Bar implementation. While Carlos H. Perez has written an excellent implementation in C# (see
http://www.codeproject.com/cs/miscctrl/OutlookBar.asp), I wanted an implementation that wasn't heavily dependent upon
gdi32
,
user32
, and
comctl32
DLL's, and wasn't deeply entwined in someone's framework. Ironic, isn't it! Because I need an implementation that is better suited for the Application Automation Layer (AAL) framework, and Carlos' implementation, while very thorough, isn't well suited for the AAL vision of things. I guess this is why the wheel keeps getting re-invented--because you need different wheels for different jobs.
I'm also going to do something I don't see too often in Code Project articles. Most articles are written "after the fact". That is, the component or program is already implemented, and the article describes its design, usage, and interesting implementation details. In this article, I'm going to expose the development process so that the reader sees the steps that I took in implementing the control. It's certainly fun to write an article in this manner, and I hope it's just as fun to read it!
I'll start with requirements. This is about the only formal design process step to which I conform, and even that is problematic, as requirements are a continually evolving thing in my world. In order to limit the amount of time I spend on something, I have to identify what my minimum requirements are. I depend heavily on working the concept that the architecture that I develop will accommodate additional requirements as time goes on.
I find it useful to identify in the requirements both what I need and what I don't need. The "don't need" list is a good resource for keeping track of future expansion and helps to design a good architecture to support those future requirements. One general requirement though--while I'm eventually going to incorporate the control into the AAL, I'd like to develop it outside of the framework, so that others can more easily modify it and incorporate it into their own applications.
- The control has a specifiable but fixed width
- The control has a specifiable but fixed height
- The control contains an number of "bands"
- A band consists of two things: a button-like control at the top of the band and a collection of items
- Each item in the band has an icon associated with it
- Left clicking on the item in the band fires an event
- Stay within the confines of the .NET environment. (No DllImport stuff)
- XML defined--band text, icon bitmaps, event names
- Owner drawn stuff should be minimized and the control should look good when a manifest is being used.
- Resizing the control and the issues that are involved
- Large and small icon support
- Those cute little band scrolling buttons. I like scroll bars better, anyways.
- Popup context menus
- Animation (the band "opens" in an animated fashion)
- A form designer compatible control. Don't use it, don't need it.
- Other kinds of controls in the band other than icons.
- Bands cannot be re-ordered by the user (dragging them to change their order).
That's sufficient to begin with. As I start developing the control, this list will probably change. (It's interesting writing this, because I haven't begun work on the control yet, so I don't really know if this is true, but experience has shown that it always is true!
This step involves getting a basic architecture to support the requirements. Since one of the goals is to stay within the .NET framework of available tools, the primary device for implementing an Outlook bar will be panels. One of the nice things about panels is that they provide an automatic scrolling feature for their contents. And fortunately, this auto-scroll capability can also be turned off. I am a firm believer (having it drilled into me by my boss/neighbor when I was a kid) that concepts should be communicated in words as well as in pictures. By being able to clearly communicate a design in words, a dictionary of terms is established which promotes a common understanding of design concepts and is a stepping stone for determining implementation issues.
With that in mind, the basic architecture that I have in mind is this:
- The entire bar will be implemented as a panel (we'll call it the "bar panel") with auto-scrolling disabled
- Each bar will consist of a child "band panel" that contains the band caption represented as a button. This panel will also have auto-scrolling disabled. The panel will be sized to the height of the button when the band is unselected, and will be expanded vertically to the size of the parent panel when expanded
- An "icon panel" will be used as a child to the above panel. It will be physically positioned so that it starts just below the button in the parent panel. This panel will have auto-scrolling enabled, as it will contain the icons that may expand beyond the vertical confines of the entire band.
- From a design point of view, this icon panel needs to be abstracted sufficiently to support other kinds of panels, such as "tree view panel" or "list view panel" (see Carlos' implementation).
- While I'm not going to bother with small and large icon support in this version, implementing an image list is a good idea, if for no other reason than because it supports background color definition.
Here's a picture of what I have in mind:
The horizontal and vertical extents of each panel are for illustrative purposes only and won't necessarily match the actual implementation.
Now that the layout of the GUI components as been developed, the next step is to design an object model that supports this structure. There is a rule of thumb that I use when working with any pre-existing classes, as is the case here (buttons and panels). Always provide a specialization for the class (as in, a derived class) or a wrapper for the object. While I do violate this rule more than I'd like to admit, it is a good one to follow, because it allows for the expansion of the object model at a later time. If the pre-existing class is used directly, it is almost always certain that later on in the design some specialization will be required. Adding specialization later, in the midst of implementation, can result in lots of class renaming and re-testing. Refactoring, whenever it is done, is a great idea, but it can be really expensive.
The question then becomes whether to implement a specialized class or a wrapper class. There are some old terms for this that are still useful but not too often heard anymore--"is a kind of" and "has a". These represent specialization and wrapping, respectively. In many cases, it's pretty difficult to figure out which to use, as is the case here. To help with that decision, I often rely on an analysis of the semantics used to describe the problem. In this case, each object, the bar panel, the band panel, and the icon panel, are all forms of specialization. If these objects are derived from the Panel class, the architecture can leverage (don't you love that word) the Panel control collection. This avoids implementing a separate collection (contrast this to Carlos' implementation, which has a band collection and an item collection). Hopefully, this design decision will not bite us later on. Why do I say this? Because experience has taught me not to rely too heavily on framework functionality. There are often unwanted side-effects.
Again, by observing the semantics of the GUI component layout and the diagram, it is clear where the "has a" relationships are:
- The bar panel object has a band panel
- the band panel has a button and a icon panel
- the icon panel has a collection of icons.
Some of the "has a" relationships are in the form of containers, which brings up the important issue of determining the m to n relationship of objects:
- The bar panel to band panel relationship is 1::n
- The band panel to button relationship is 1::1
- The band to icon panel relationship is 1::1
- The icon panel to icon relationship is 1::n
While I pretty much don't bother with object model diagrams anymore, I put this one together:
I usually don't specify methods and intrinsic properties during design time when developing on my own because it's sort of a waste of time. As a project manager, I don't enforce these definitions at design time either with the people I trust. The programmers that I don't trust to write good code (and there's a lot of "senior software engineers" out there that fit this bill) are required to come up with a complete object model design and psuedo code. I also enforce naming conventions, case usage, and verb-noun ordering of method names. And for the record, I think Hungarian notation is awful.
Using the above diagram results in the following stubs for the various objects. Because the
Panel.Controls
property is used for containing the control lists, you will not see containers or collections implemented in the class definition.
using System;
using System.Windows.Forms;
namespace OutlookBar
{
public class OutlookBar : Panel
{
public OutlookBar()
{
}
}
internal class BandPanel : Panel
{
public BandPanel()
{
}
}
internal class BandButton : Button
{
public BandButton()
{
}
}
public abstract class ContentPanel : Panel
{
public ContentPanel()
{
}
}
public class IconPanel : ContentPanel
{
public IconPanel()
{
}
}
internal class PanelIcon : PictureBox
{
public PanelIcon()
{
}
}
}
Note that the
IconPanel
class is public. This allows the application to instantiated the desired band types (of which, IconPanel is the only one provided in this implementation). Now let's start fleshing out some of the details, starting with the
OutlookBar
class.
First, the OutlookBar
needs to be instantiated so that it appears on the form. Creating a new project, I modified the Form1
constructor to instantiate the OutlookBar
, and specified a border style so that its creation and placement can be verified:
public Form1()
{
InitializeComponent();
OutlookBar outlookBar=new OutlookBar();
outlookBar.Location=new Point(0, 0);
outlookBar.Size=new Size(150, this.ClientSize.Height);
outlookBar.BorderStyle=BorderStyle.FixedSingle;
Controls.Add(outlookBar);
}
Success!
The First Band
Next, methods must be added for creating the bands. This requires specifying the text and the type of band. To keep things simple, the application will be responsible for instantiating the desired band type. This thrusts the implementation immediately into some complex issues of sizing and positioning, but as always, starting simple is the best idea.
The enhancements to the OutlookBar
class is straightforward:
public class OutlookBar : Panel
{
private int buttonHeight;
public int ButtonHeight
{
get
{
return buttonHeight;
}
set
{
buttonHeight=value;
}
}
public OutlookBar()
{
buttonHeight=25;
}
public void AddBand(string caption, ContentPanel content)
{
BandPanel bandPanel=new BandPanel(caption, content);
Controls.Add(bandPanel);
RecalcLayout(bandPanel);
}
private void RecalcLayout(BandPanel bandPanel)
{
bandPanel.Location=new Point(0, 0);
bandPanel.Size=new Size(ClientRectangle.Width, buttonHeight);
bandPanel.Controls[0].Location=new Point(0, 0);
bandPanel.Controls[0].Size=new Size(ClientRectangle.Width, buttonHeight);
bandPanel.Controls[1].Location=new Point(0, buttonHeight);
bandPanel.Controls[1].Size=new Size(ClientRectangle.Width, 0);
}
}
And results in the following display:
In this implementation, the button height is identified as a parameter that might be useful to externalize so that it is under the control of the application. Obviously, when the button height is changed after the Outlook bar has been created, the entire bar and its children will have to be recalculated.
The RecalcLayout
method for the band is a simple starting point for determining the dimensions of the button and the associated content panel. This method has been placed in the OutlookBar
class because other information contained only in the OutlookBar
will be used soon--namely, the band's index.
This implementation allows for adding one band to the bar. That's a good starting point, as details such as activating and deactivating a band can be worked out at this point. Also notice that this implementation raises some questions not answered in the specifications:
- Are all the bands added at one time during initialization?
- Can bands be removed?
- Can bands be added later, when the application is running?
- Should the insertion point be specified when adding bands?
This is typical of any specification. During implementation, questions always arise that are not answered in the spec, no matter how well thought out. In the particular case of this prototype, the answers are yes, no, no, no, respectively. Sure makes life easier!
Multiple Bands
It will be more interesting to deal with the expansion and contraction of a band if the prototype first allows for multiple bands. This is easily done by keeping track of how many bands have been added, and passing the band's index relative to the other bands to the <code>RecalcLayout</code> method. The OutlookBar.Controls.Count
property provides the necessary information. Because the band's button and content control's are child controls, these are relative to the band position, so only the band position needs to be modified. The changes are quite simple:
public void AddBand(string caption, ContentPanel content)
{
BandPanel bandPanel=new BandPanel(caption, content);
Controls.Add(bandPanel);
RecalcLayout(bandPanel, Controls.Count-1);
}
private void RecalcLayout(BandPanel bandPanel, int index)
{
bandPanel.Location=new Point(0, buttonHeight*index);
bandPanel.Size=new Size(ClientRectangle.Width, buttonHeight);
bandPanel.Controls[0].Location=new Point(0, 0);
bandPanel.Controls[0].Size=new Size(ClientRectangle.Width, buttonHeight);
bandPanel.Controls[1].Location=new Point(0, buttonHeight);
bandPanel.Controls[1].Size=new Size(ClientRectangle.Width, 0);
}
resulting in:
Activating A Band
Activating a band requires keeping track of the band index that is active and recalculating the layout of the entire bar when a band is activated. Firstly, this requires handling the button click event. A single event sink will be used for all the buttons, so the button needs to have some information about itself so that it can notify the OutlookBar
that it's associated band should be selected. This information is preserved in the instance of the button itself. (Events are a wonderful thing in the .NET framework, and one feature is that events can be associated with an instance of an object). A variety of information might want to be associated with the band's button, but for now the index and OutlookBar
instance will suffice. A simple class can handle this:
internal class BandTagInfo
{
public OutlookBar outlookBar;
public int index;
public BandTagInfo(OutlookBar ob, int index)
{
outlookBar=ob;
this.index=index;
}
}
And the following modification is made to the
AddBand
method:
public void AddBand(string caption, ContentPanel content)
{
int index=Controls.Count;
BandTagInfo bti=new BandTagInfo(this, index);
BandPanel bandPanel=new BandPanel(caption, content, bti);
Controls.Add(bandPanel);
RecalcLayout(bandPanel, index);
}
Incidentally, the rest of the classes are still simple stubs for initializing various state information:
internal class BandPanel : Panel
{
public BandPanel(string caption, ContentPanel content, BandTagInfo bti)
{
BandButton bandButton=new BandButton(caption, bti);
Controls.Add(bandButton);
Controls.Add(content);
}
}
internal class BandButton : Button
{
private BandTagInfo bti;
public BandButton(string caption, BandTagInfo bti)
{
Text=caption;
FlatStyle=FlatStyle.Standard;
Visible=true;
this.bti=bti;
}
}
public abstract class ContentPanel : Panel
{
public ContentPanel()
{
Visible=false;
}
}
internal class IconPanel : ContentPanel
{
public IconPanel()
{
}
}
internal class PanelIcon : PictureBox
{
public PanelIcon()
{
}
}
As is evident, the
BandTagInfo
object is passed down to the
BandButton
constructor, which is preserved by the button instance. The event handler can now be declared and associated with the button click, which then invokes a method in the appropriate instance of the
OutlookBar
class to perform the actual selection:
internal class BandButton : Button
{
private BandTagInfo bti;
public BandButton(string caption, BandTagInfo bti)
{
Text=caption;
FlatStyle=FlatStyle.Standard;
Visible=true;
this.bti=bti;
Click+=new EventHandler(SelectBand);
}
private void SelectBand(object sender, EventArgs e)
{
bti.outlookBar.SelectBand(bti.index);
}
}
The
OutlookBar
class is enhanced to preserve the current band selection and initialize it to "no selection". A getter and setter is provided for the property. The setter invokes the same
SelectBand
method as clicking on the button:
public class OutlookBar : Panel
{
private int buttonHeight;
private int selectedBand;
public int SelectedBand
{
get
{
return selectedBand;
}
set
{
SelectBand(value);
}
}
...
The
SelectBand
method:
public void SelectBand(int index)
{
selectedBand=index;
RedrawBands();
}
void RedrawBands()
{
for (int i=0; i < Controls.Count; i++)
{
BandPanel bp=Controls[i] as BandPanel;
RecalcLayout(bp, i);
}
}
iterates through all the band controls and instructs them to recalculate their layout, so the real work is done in that method.
Time to think about some things:
- The band, when selected, has a height that is always equal to the bar height minus the height of all the buttons on the bar.
- The bands before the selected band are drawn at the top of bar.
- The bands after the selected band are drawn at the bottom of the selected band.
This makes it a little annoying to have an unselected index of "-1", as all the bands are therefore "after" some imaginary selected band. There is a really simple solution to this, which you can see in Outlook: one band is always selected! Therefore, the default selection will be index "0"--the first band. Whenever a band is added, the "selected band height" must be recalculated. This is implemented as a method because it'll be used later as part of button height changes and window size changes:
private void UpdateBarInfo()
{
selectedBandHeight=ClientRectangle.Height-(Controls.Count * buttonHeight);
}
The band layout calculation must now take into account the placement of the band, using the criteria:
- Is this band before the selected band?
- Is this band the selected band?
- Is this band after the selected band?
private void RecalcLayout(BandPanel bandPanel, int index)
{
int vPos=(index <= selectedBand) ? buttonHeight*index :
buttonHeight*index+selectedBandHeight;
int height=selectedBand==index ? selectedBandHeight : buttonHeight;
bandPanel.Location=new Point(0, vPos);
bandPanel.Size=new Size(ClientRectangle.Width, height);
bandPanel.Controls[0].Location=new Point(0, 0);
bandPanel.Controls[0].Size=new Size(ClientRectangle.Width, buttonHeight);
bandPanel.Controls[1].Location=new Point(0, buttonHeight);
bandPanel.Controls[1].Size=new Size(ClientRectangle.Width, height);
}
This results in some wonderfully functional capability and pretty much completes the band activation issue. The Outlook bar's buttons can now be clicked on, and they move around as required:
One minor detail. The AddBand
method can no longer simply set up the location and size of the newly added band, because this influences the height of the first (selected) band. As a result, the application is responsible now for selecting the desired band after all the bands have been created. Nothing like changing the rules on the fly, is there!
Application Resizing
Of major concern at this point is: what happens to the bar when the containing form is resized? For this, an event handler must be added. Another wonderful feature of .NET's event mechanism is that multiple handlers can be associated with the same event. So regardless of other resizing handlers associated with the form, the Outlook bar can add its own:
public void Initialize()
{
Parent.SizeChanged+=new EventHandler(SizeChangedEvent);
}
Unfortunately, because this must be done after the Outlook bar has been added to the form (or other control), it requires a separate initialization method so that the parent is guaranteed to exist.
The event handler itself is very straightforward. It recalculates the Outlook bar panel size, updates the selected band height, and calls the RedrawBands
method:
private void SizeChangedEvent(object sender, EventArgs e)
{
Size=new Size(Size.Width, ((Control)sender).ClientRectangle.Size.Height);
UpdateBarInfo();
RedrawBands();
}
Note that this handler only deals with vertical resizing. A separate mechanism is required if you wish to deal with horizontal resizing, for example if the control is contained in a splitter window.
Time for a little design. The icon panel should have the following features:
- Icons are placed in centered down the midline of the panel;
- Icons have captions;
- Clicking on an icon triggers an event that is supplied by the application;
- Icons are ordered from top to bottom in the order that they are added to the band;
- The icon panel defaults to a white background;
- Icons need to support transparency.
First off, setting the background color of the panel to white reveals a bug in the size calculation of the parent band panel. This is corrected to include both the button height and content panel height:
private void RecalcLayout(BandPanel bandPanel, int index)
{
int vPos=(index <= selectedBand) ? buttonHeight*index :
buttonHeight*index+selectedBandHeight;
int height=selectedBand==index ? selectedBandHeight+buttonHeight :
buttonHeight;
...
Icons in the icon panel consist of the icon image itself and a caption. Both are centered. The caption must be implemented as a
Label
contained by the
IconPanel
. Thus, for every icon in the icon panel, there are two controls created: the
PanelIcon
(derived from
PictureBox
) and the caption, which is instantiated as a
Label
. The code ends up looking like this:
public class IconPanel : ContentPanel
{
protected int iconSpacing;
protected int margin;
public int IconSpacing
{
get
{
return iconSpacing;
}
}
public int Margin
{
get
{
return margin;
}
}
public IconPanel()
{
margin=10;
iconSpacing=32+15+10;
BackColor=Color.White;
AutoScroll=true;
}
public void AddIcon(string caption, Image image, EventHandler onClickEvent)
{
int index=Controls.Count/2;
PanelIcon panelIcon=new PanelIcon(this, image, index, onClickEvent);
Controls.Add(panelIcon);
Label label=new Label();
label.Text=caption;
label.Visible=true;
label.Location=new Point(0, margin+image.Size.Height+index*iconSpacing);
label.Size=new Size(Size.Width, 15);
label.TextAlign=ContentAlignment.TopCenter;
label.Click+=onClickEvent;
label.Tag=panelIcon;
Controls.Add(label);
}
}
public class PanelIcon : PictureBox
{
public int index;
public IconPanel iconPanel;
public PanelIcon(IconPanel parent, Image image, int index,
EventHandler onClickEvent)
{
this.index=index;
this.iconPanel=parent;
Image=image;
Visible=true;
Location=new Point(iconPanel.outlookBar.Size.Width/2 -
image.Size.Width/2,
iconPanel.Margin + index*iconPanel.IconSpacing);
Size=image.Size;
Click+=onClickEvent;
Tag=this;
}
}
Note that both the
PictureBox
and the
Label
can be clicked. The
Tag
property is set to the
PanelIcon
in both cases, should the application require some additional information regarding the sender of the event.
Incidentally, changing the background to some other color verifies that icon transparency is functioning correctly.
During this implementation of the icon bar, certain design issues have come up:
- Can the application specify the caption font?
- Can the application specify the caption color?
- Can the application change the background color of the panel? What about textures?
- Changing the bar width is going to require a lot of recalculations for text and icon centering.
- There are no setter functions for the vertical margin and the icon spacing.
- The icon spacing needs to be adjusted if we plan to support large icons.
- The icon spacing is hard coded and assumes an icon size of 32x32.
These are all valid issues, but for my needs right now, I don't need to consider them. (I'd rather go walking on the beach, in other words).
The current implementation results in a nice presentation:
For some reason, the scroll bar was slightly off screen to the right and the slightly too long. The correct appearance:
is only achieved by modifying the dimensions of that content panel:
bandPanel.Controls[1].Size=new Size(ClientRectangle.Width-2, height-8);
which I have no explanation for, as the size is being determined by the client area of the band panel. If anyone else has some ideas, let me know!
I wanted to implement one piece of "eye candy", which is to highlight the icon background when the mouse enters the icon area. My first implementation was straightforward, adding MouseEnter
and MouseLeave
event handlers to the PanelIcon
class:
private void OnMouseEnter(object sender, EventArgs e)
{
BackColor=Color.LightCyan;
BorderStyle=BorderStyle.FixedSingle;
Location=Location-new Size(1, 1);
}
private void OnMouseLeave(object sender, EventArgs e)
{
BackColor=bckgColor;
BorderStyle=BorderStyle.None;
Location=Location+new Size(1, 1);
}
Note that in this code, I'm also setting the border style. When I first set just the background, everything worked great. When I added turning on and off a border around the icon, things started to go wrong. First off, the icon shifted right and down by one pixel, which wasn't too pleasing visually. Secondly, the border wouldn't disappear if the mouse left the icon from the right or the bottom edge. To fix the shifting of the icon, I simply moved to location up and to the left on entry and back down and to the right on exit. However, the icon background was still not being cleared properly, and this only happened when a border was specified. As it turns out, the problem has to do with the border, and the fact that as soon as the
OnMouseLeave
event is called and the icon is repositioned (forward and down), this results in the
OnMouseEnter
event being called. Subsequently, there is no corresponding
OnMouseLeave
called again!
The fix to this was to "enter" the icon at a slightly smaller size, using the MouseMove
event to determine the mouse position, and to set up a flag to keep track of whether the mouse was "entered" or not. The following code illustrates the solution:
private void OnMouseMove(object sender, MouseEventArgs args)
{
if ( (args.X < Size.Width-2) &&
(args.Y < Size.Width-2) &&
(!mouseEnter) )
{
BackColor=Color.LightCyan;
BorderStyle=BorderStyle.FixedSingle;
Location=Location-new Size(1, 1);
mouseEnter=true;
}
}
private void OnMouseEnter(object sender, EventArgs e)
{
}
private void OnMouseLeave(object sender, EventArgs e)
{
if (mouseEnter)
{
BackColor=bckgColor;
BorderStyle=BorderStyle.None;
Location=Location+new Size(1, 1);
mouseEnter=false;
}
}
This code works great, and now I have a lovely highlighted icon with a border around it when the mouse enters the icon:
What? That's it? Yes, that's it. I now have a lovely icon Outlook bar that is quite sufficient for my needs. There's lots of room for expansion (and error checking!), but those things can be added in later. Enough goofing around, it's time to use this thing in my client's application and get some billable hours on the books.
For those interested, the sample bar is generated using a few lines of code in the Form
constructor:
OutlookBar outlookBar=new OutlookBar();
outlookBar.Location=new Point(0, 0);
outlookBar.Size=new Size(150, this.ClientSize.Height);
outlookBar.BorderStyle=BorderStyle.FixedSingle;
Controls.Add(outlookBar);
outlookBar.Initialize();
IconPanel iconPanel1=new IconPanel();
IconPanel iconPanel2=new IconPanel();
IconPanel iconPanel3=new IconPanel();
outlookBar.AddBand("Outlook Shortcuts", iconPanel1);
outlookBar.AddBand("My Shortcuts", iconPanel2);
outlookBar.AddBand("Other Shortcuts", iconPanel3);
iconPanel1.AddIcon("Outlook Today", Image.FromFile("img1.ico"),
new EventHandler(PanelEvent));
iconPanel1.AddIcon("Calendar", Image.FromFile("img2.ico"),
new EventHandler(PanelEvent));
iconPanel1.AddIcon("Contacts", Image.FromFile("img3.ico"),
new EventHandler(PanelEvent));
iconPanel1.AddIcon("Tasks", Image.FromFile("img4.ico"),
new EventHandler(PanelEvent));
outlookBar.SelectBand(0);
Enjoy!