http://www.codeproject.com/KB/selection/MonthCalendar.aspx
- Download source files (VS 2003) - 81.4 Kb
- Download demo (.NET 1.1) - 66.8 Kb
- Download source files (VS 2005) - 84.3 Kb
- Download demo (.NET 2.0) - 67.4 Kb
Introduction
I decided to write this control because I needed a month calendar that's much more customizable and flexible than the standard Visual Studio Calendar, in one of my projects. My primary focus was the ability to add information (color, text, image etc.) to each day, and for this to work reasonably well, it must also be resizable.
This is my second article for CodeProject, and it shares some of the implementation techniques of the previous article, so if you want some detail on the implementation of themes, nested properties, and TypeEditors, check out my MozBar article. For information about how to edit and persist collections, check out Daniel Zaharia's excellent article.
Using the control
Like any other .NET control, for using in the IDE, you should add the
MonthCalendar
control to the Toolbox panel. This can be accomplished by right-clicking on a Toolbox tab and selecting "Add/Remove items...", browsing to the
MonthCalendar
assembly, and selecting it. This will add the
MonthCalendar
control to the Toolbox so that it can be dragged/dropped to a Windows Form.
Once an instance of
MonthCalendar
is added to the form, select it and view its properties.
Layout and design
The basic design for the control is pretty much like the standard Visual Studio
Calendar
, but it is a lot more flexible. To make it more portable and to reduce the overhead, everything is drawn directly with GDI.
MonthCalendar
basically consists of five different regions, each with its own set of properties.
The only region that must be visible is the month region, all the others can be switched on or off.
Properties
The following properties control the most significant behavior and the look and feel of the
MonthCalendar
control:
-
: Color used for the border.BorderColor
-
: The style used for the border.BorderStyle
-
: Indicates whether the footer should be visible (default=ShowFooter
).true
-
: Indicates whether the header should be visible (default=ShowHeader
).true
-
: Indicates whether weekdays should be visible (default=ShowWeekdays
).true
-
: Indicates whether week numbers should be visible (default=ShowWeeknumbers
).false
-
: The color used for the circle that marks today's date.TodayColor
-
: The month currently shown in the calendar.ActiveMonth
-
: The culture used for the calendar.Culture
-
: A collection of formatted dates.Dates
-
: TheImageList
used to hold images for the calendar, this must be set if you want to assign images to dates.ImageList
-
: The maximum date that can be selected.MaxDate
-
: The minimum date that can be selected.MinDate
-
: Collection of selected dates.SelectedDates
-
: Indicates the selection mode used in the calendar (SelectionMode
,None
,One
, orMultiSimple
).MultiExtended
-
: The key used for the extended selection mode.ExtendedSelectionKey
-
: Sets the first day of week for the current culture.FirstDayOfWeek
-
: The mouse button used for selections.SelectButton
-
: Indicates whether selecting trailing dates is possible (default=SelectTrailingDates
).true
-
: Toggles hot tracking when moving the mouse over a date (default=ShowFocus
).true
-
: Indicates if today's date should be marked, the color used for the mark is the one assigned toShowToday
(default=TodayColor
).true
-
: Indicates whether trailing dates should be visible or not (default=ShowTrailingDates
).true
-
: Indicates whether the calendar should use theme colors (default=Theme
).false
-
: Indicates whether keyboard support is enabled (default=KeyboardEnabled
).true
-
: Collection of keys used for keyboard control.Keyboard
-
: Returns the version number.Version
Month
-
: Image used as background.BackgroundImage
-
: Text and background transparency (used when painting colors).Transparency
-
: Indicates whether formatting should be shown for trailing dates (default=FormatTrailing
).true
-
: Vertical and horizontal spacing.Padding
-
: Date alignment within a day.DateAlign
-
: Indicates whether the first and the last day of a month should have the month displayed in the date (default=ShowMonthInDay
).false
-
: Text alignment within a day.TextAlign
-
: Enables theEnableImageClick
event (default=ImageClick
).false
-
: Image alignment within a day.ImageAlign
-
: Font used for the date.DateFont
-
: Font used for the text.TextFont
-
: Collection of colors used in the calendar.Colors
-
: Collection of border styles used in the calendar.BorderStyles
Header
-
: Alignment of the month/text in the header.Align
-
: Indicates whether the next/previous month button should be visible (default=MonthSelectors
).true
-
: Indicates whether the next/previous year button should be visible (default=YearSelectors
).false
-
: Indicates if the month name should be visible in the header (default =ShowMonth
).true
-
: The text to be displayed in the header (ifText
isShowMonth
).false
-
: The color used for the header background.BackColor1
-
: The second color used for background when using a gradient.BackColor2
-
: Type of gradient used.GradientMode
-
: The font used for the month/text.Font
-
: The color used for the month/text.TextColor
-
: Indicates whether a month selection menu should be displayed while right-clicking the header (default =MonthContextMenu
).true
Footer
-
: The text alignment for the footer.Align
-
: The text to be displayed in the footer, ifText
isShowToday
.false
-
: Indicates whether today's date should be displayed in the footer (default=ShowToday
).true
-
: The format used for today's date.Format
-
: The color used for the header background.BackColor1
-
: The second color used for background when using a gradient.BackColor2
-
: Type of gradient used.GradientMode
-
: The font used for the date/text.Font
-
: The color used for the date/text.TextColor
Weekdays
-
: The color used for the border.BorderColor
-
: The color used for the header background.BackColor1
-
: The second color used for background when using a gradient.BackColor2
-
: Type of gradient used.GradientMode
-
: The font used for weekdays.Font
-
: The color used for weekdays.TextColor
-
: The format used to display weekdays.Format
-
: Text alignment for weekdays.Align
Weeknumbers
-
: The color used for the border.BorderColor
-
: The color used for the header background.BackColor1
-
: The second color used for background when using a gradient.BackColor2
-
: Type of gradient used.GradientMode
-
: The font used for week numbers.Font
-
: The text color used for week numbers.TextColor
-
: Text alignment for week numbers.Align
Events
The most useful events are:
Month
-
: Indicates that the active month was changed.MonthChanged
-
: Raised before a month is displayed. Use this event to prevent the selection of certain months.BeforeMonthChanged
-
: Indicates that data was dropped on a day,DayDragDrop
must beAllowDrop
for this event to be raised.true
-
: Indicates that an image was clicked.ImageClick
-
: Indicates that a day was clicked.DayClick
-
: Occurs before a date is updated.DayRender
-
: Occurs before a date is updated.DayQueryInfo
-
: Indicates that a day was double clicked.DayDoubleClick
-
: Indicates that one or more days were selected.DaySelected
-
: Raised before a day is selected. Use this event to prevent selection of days.BeforeDaySelected
-
: Indicates that one or more days were deselected.DayDeselected
-
: Raised before a day is deselected. Use this event to prevent deselection of days.BeforeDayDeselected
-
: Indicates that a day received focus.DayGotFocus
-
: Indicates that a day lost focus.DayLostFocus
-
: Indicates that the mouse is moved inside a day.DayMouseMove
Header
-
: Indicates that the header was clicked.HeaderClick
-
: Indicates that the header was double clicked.HeaderDoubleClick
-
: Indicates that the mouse entered the header region.HeaderMouseEnter
-
: Indicates that the mouse left the header region.HeaderMouseLeave
Footer
-
: Indicates that the footer was clicked.FooterClick
-
: Indicates that the footer was double clicked.FooterDoubleClick
-
: Indicates that the mouse entered the footer region.FooterMouseEnter
-
: Indicates that the mouse left the footer region.FooterMouseLeave
Weekday
-
: Indicates that a weekday was clicked.WeekdayClick
-
: Indicates that a weekday was double clicked.WeekdayDoubleClick
-
: Indicates that the mouse entered the weekday region.WeekdayMouseEnter
-
: Indicates that the mouse left the weekday region.WeekdayMouseLeave
Weeknumber
-
: Indicates that a week was clicked.WeeknumberClick
-
: Indicates that a week was double clicked.WeeknumberDoubleClick
-
: Indicates that the mouse entered the week number region.WeeknumberMouseEnter
-
: Indicates that the mouse left the week number region.WeeknumberMouseLeave
As usual, when using events, the supplied
eventArgs
parameter contains the properties useful for that particular event.
Methods
The following methods are supported:
Date formatting
-
: Adds an array of formatted dates.void AddDateInfo(DateItem[] info)
-
: Removes thevoid RemoveDateInfo(DateTime dt)
associated with the supplied date.DateItem
-
: Removes the suppliedvoid RemoveDateInfo(DateItem item)
.DateItem
-
: Adds a formatted date.void AddDateInfo(DateItem info)
-
: Removes all date formatting.void ResetDateInfo()
-
: Returns all the formatted dates.DateItem[] GetDateInfo()
-
: Returns an array ofDateItem[] GetDateInfo(DateTime dt)
s matching the supplied date.DateItem
Selection
-
: Selects the supplied date. The date must be betweenvoid SelectDate(DateTime d)
andMinDate
.MaxDate
-
: Clears the existing selection.void ClearSelection()
-
: Returnsbool IsSelected(DateTime dt)
if the supplied date is selected, otherwisetrue
.false
-
: Selects the area described by the two dates.void SelectArea(DateItem topleft, DateItem bottomright)
-
: Deselects the area described by the two dates.void DeselectArea(DateItem topleft, DateItem bottomright)
-
: Selects the range described by the two dates.void SelectRange(DateItem from, DateItem to)
-
: Deselects the range described by the two dates.void DeselectRange(DateItem from, DateItem to)
-
: Selects every day in the supplied week.void SelectWeek(int week)
-
: Deselects every selected day in the supplied week.void DeselectWeek(int week)
-
: Selects everyvoid SelectWeekday(DayOfWeek day)
in the current month.DayOfWeek
-
: Deselects every selectedvoid DeselectWeekday(DayOfWeek day)
in the current month.DayOfWeek
Misc.
-
: Prints the current calendar on the default printer.void Print()
-
: Returns a bitmap of the current calendar.Bitmap Snapshot()
-
: Saves the calendar to a file.void SaveAsImage(string filename, ImageFormat format)
-
: Copies the calendar to the clipboard.void Copy()
Adding date formatting
You can add formatted dates either during runtime by using one of the
DateInfo
methods, or in design mode by using the built-in
DateItemCollection
.
Adding date formatting in design mode is, of course, not very practical for real applications, your info will most likely be stored in some kind of database, so the best way to add date formatting is to respond to the
MonthChanged
event and add the dates during runtime:
Collapse
Copy Code
private void monthCalendar1_MonthChanged(object sender,
Pabo.Calendar.MonthChangedEventArgs e)
{
AddInfo(e.Year,e.Month);
}
To add formatted dates during runtime, you need to create
DateItem
objects. A
DateItem
has several properties that define the appearance of the date:
-
: The date for which the info applies.Date
-
: The image used as background.BackgroundImage
-
: The color used for background.BackColor1
-
: The second color used for background when using a gradient.BackColor2
-
: Type of gradient used.GradientMode
-
: Indicates whether the date should be handled as a weekend (default =Weekend
).false
-
: Color used for the date.DateColor
-
: Color used for the text.TextColor
-
: Index for the image to be displayed in the date. For this to work, anImageListIndex
must be assigned to theImageList
.MonthCalendar
-
: Image to be displayed in the date. If this property is set, it will override theImage
.ImageList
-
: Indicates if the date should use a bold font (default =BoldedDate
).false
-
: Indicates whether the date is enabled or not. A date that is disabled is not selectable, and will be drawn using the disabled colors. Any image will be drawn in a disabled state (default =Enabled
).true
-
: Describes the recurring pattern used for thisPattern
(default =DateItem
).None
-
: Describes the maximum range (end date) for the recurring pattern.Range
Creating and adding
DateItem
s could look something like this:
Collapse
Copy Code
private void FormatDates()
{
DateItem[] d = new DateItem[5];
d.Initialize();
for (int i = 0;i<5;i++)
d[i] = new DateItem();
d[0].Date = new DateTime(2005,6,3);
d[0].BackColor1 = Color.Red;
d[0].ImageListIndex = 3;
d[0].Text = "Help";
d[1].Date = new DateTime(2005,6,12);
d[1].ImageListIndex = 2;
d[2].Date = new DateTime(2005,6,16);
d[2].BackColor1 = Color.LightBlue;
d[2].ImageListIndex = 8;
d[3].Date = new DateTime(2005,6,18);
d[3].BackColor1 = Color.GreenYellow;
d[3].ImageListIndex = 1;
d[3].Text = "NorDev";
d[4].Date = new DateTime(2005,6,22);
d[4].ImageListIndex = 1;
d[4].Text = "Cebit";
monthCalendar1.AddDateInfo(d);
}
If you don't want to add a lot of
DateItem
s at once, you can use the
DayQueryInfo
event and add formatting depending on the date. The
DayQueryInfo
event is raised before each date is rendered, and makes it possible to supply date formatting using the
DateItem
properties.
Collapse
Copy Code
private void monthCalendar1_DayQueryInfo(object sender,
DayQueryInfoEventArgs e)
{
// Check date
if (e.Date.DayOfWeek == DayOfWeek.Thursday)
{
// Add custom formatting
e.Info.BackColor1 = Color.Yellow;
e.Info.BackColor2 = Color.GhostWhite;
e.Info.ImageListIndex = 3;
e.Info.GradientMode = mcGradientMode.Horizontal;
// Set ownerdraw = true to add custom formatting
e.OwnerDraw = true;
}
}
Note that you must set
OwnerDraw
=
true
to add formatting, and the formatting added by this event is overridden by the
DayRender
event if that is used.
Recurring dates
MonthCalendar
supports basic recurring date formatting. This functionality is controlled by the
Pattern
and
Range
properties.
The following patterns can be applied to a
DateItem
:
-
: No recurring pattern is applied (default), the formatting is only valid for the day specified by theNone
property.Date
-
: The formatting will be applied to every day within theDaily
.Range
-
: The formatting will be applied to every same weekday within theWeekly
.Range
-
: The formatting will be applied to the same day each month within theMonthly
.Range
-
: The formatting will be applied to the same day every year within theYearly
.Range
Note that there is no "collision detection", so overlapping patterns will be drawn on top of each other. You can use functions like
GetDateInfo
to check which
DateItem
s are applied to a certain date. The
Range
and
Pattern
properties do not have any impact when set through the
DayQueryInfo
event.
Owner-drawn dates
If the built-in formatting doesn't give you the appearance you want, then you can provide your own by using the
DayRender
event. The
DayRender
event is raised before each date in the calendar is painted. You can control the contents and formatting of a date by providing code in the event handler for the
DayRender
event. To make the date owner-drawn, set
DayRenderEventArs.OwnerDraw=true
:
Collapse
Copy Code
private void monthCalendar1_DayRender(object sender,
Pabo.Calendar.DayRenderEventArgs e)
{
Brush bgBrush = new SolidBrush(Color.White);
Brush dateBrush = new SolidBrush(Color.Black);
Font dateFont = new Font("Microsoft Sans Serif",(float)8.25);
StringFormat dateAlign = new StringFormat();
dateAlign.Alignment = StringAlignment.Far;
dateAlign.LineAlignment = StringAlignment.Near;
Rectangle rect = new Rectangle(0,0,e.Width,e.Height);
// Set OwnerDraw = true to override built in formatting...
e.OwnerDraw = true;
// ...then Draw the appearance of the date
e.Graphics.FillRectangle(bgBrush,rect);
e.Graphics.DrawString(e.Date.Day.ToString(),
dateFont,dateBrush,rect,dateAlign);
// Clean up
bgBrush.Dispose();
dateBrush.Dispose();
dateAlign.Dispose();
dateFont.Dispose();
}
Note that using the
DayRender
event to draw the appearance of a date completely overrides all other formatting done by the control for the specific date.
Multi-select ala Excel
One thing I wanted to add to the control was multi-select. The problem with this is that when selected days have different colors for border and background, then it doesn't look very nice drawing all the selected days individually, and drawing the days as selected will also cover the previous backcolor; so what you have to do is draw the entire selected area with one transparent background and one border ala Excel. So, how can we do this?
It's pretty simple. The month region basically consists of an array of days, each with its own rectangle, so what we need is the start and the end day for the selection so that we can construct our "selection" rectangle. When the user clicks on a day, we set the start day (
m_selStart
). And when the mouse is pressed and moved over a new day (that can be selected), we set the end day (
m_selEnd
). When drawing the selection, we only need to get the coordinates for the selection area and draw it with the desired transparent color.
Collapse
Copy Code
// Check if an selection exist
if (m_selectedDays.Length>0)
{
Brush selBrush = new SolidBrush(Color.FromArgb(125,
Colors.SelectedBackground));
// Get Coordinates for selection rectangle
m_selRight = System.Math.Max(m_days[m_selStop].Rectangle.Right,
m_days[m_selStart].Rectangle.Right);
m_selLeft = System.Math.Min(m_days[m_selStop].Rectangle.Left,
m_days[m_selStart].Rectangle.Left);
m_selTop = System.Math.Min(m_days[m_selStop].Rectangle.Top,
m_days[m_selStart].Rectangle.Top);
m_selBottom = System.Math.Max(m_days[m_selStop].Rectangle.Bottom,
m_days[m_selStart].Rectangle.Bottom);
// Draw selection
Rectangle selRect = new Rectangle(m_selLeft,m_selTop,
m_selRight-m_selLeft,m_selBottom-m_selTop);
e.FillRectangle(selBrush,selRect);
ControlPaint.DrawBorder(e,selRect,Colors.SelectedBorder,
BorderStyles.Selected);
selBrush.Dispose();
}
Easy indeed, but I think it adds a nice touch to the control.
Different selection modes
MonthCalendar
supports the following selection modes indicated by the
SelectionMode
property:
-
: No selection is possible.None
-
: Only one date can be selected at a time.One
-
: A continuous block of dates can be selected.MultiSimple
-
: Same asMultiExtended
, but pressing a key enables selection/deselection of discontinuous dates. You can set the key used, with theMultiSimple
property.ExtendedSelectionKey
When selecting/deselecting dates in code, make sure that the appropriate
SelectionMode
is set; when deselecting more than one date, it must be set to
MultiExtended
, and when selecting more than one date, at least
MultiSimple
is required.
Retrieving selected/deselected days
When selecting/deselecting dates, the
DaySelected
and
DayDeselected
events are raised. To retrieve the days, you can either use the information contained in the
DaySelectedEventArgs
, or use the
SelectedDates
collection. Getting the dates selected by the user could look something like this:
Collapse
Copy Code
private void monthCalendar1_DaySelected(object sender,
Pabo.Calendar.DaySelectedEventArgs e)
{
// Using the days from the EventArgs
string[] m_daysSelected = e.Days;
// Using SelectedDates
SelectedDatesCollection m_dates = monthCalendar1.SelectedDates;
}
Dynamically created dropdown in PropertyGrid
Sometimes, you want to provide the user with a list of possible choices for a property. One way to do this is to use enumerations which automatically provide you with a dropdown with the possible choices. But this solution is static, the list will always have the same content. What if you want the choices to change depending on other choices the user makes?
The solution is to create a custom
TypeConverter
and override some functions that will let us supply our own values through the
StandardValuesCollection
.
GetStandardValuesSupported
decides if standard values are supported. Returning
true
means it's supported:
Collapse
Copy Code
public override bool GetStandardValuesSupported(
ITypeDescriptorContext context)
{
// return true to allow standard values.
return true;
}
GetStandardValuesExclusive
decides if the user should be allowed to type values or not. Returning
false
means typing is allowed:
Collapse
Copy Code
public override bool GetStandardValuesExclusive(
ITypeDescriptorContext context)
{
// Allow user to enter values with keyboard
return false;
}
Now, all we have to do is override
GetStandardValuesCollection
and return the list that we want to use:
Collapse
Copy Code
public override System.ComponentModel.TypeConverter.StandardValuesCollection
GetStandardValues(ITypeDescriptorContext context)
{
activeMonth m = (activeMonth)context.Instance;
return new StandardValuesCollection(m.Calendar.AllowedYears());
}
You will also need to override
OnConvertFrom
and
OnConvertTo
to validate the input, and if you don't inherit from
StringConverter
, you must override
CanConvertFrom
and
CanConvertTo
as well.
Week number
Calculating week number is somewhat problematic since different countries in the world have different rules associated with their calendars. In most parts of Europe, we calculate week number according to the ISO8601 calendar, which means we use the FirstFourDayWeek rule and Monday as the first day of the week. Using these settings and the Swedish culture with the
GetWeekOfYear
function found in
System.Globalization.Calendar
doesn't always give you the correct week (according to ISO8601), so it seems there are bugs in the .NET week calculation routines.
Looking around, I found a webpage that describes this problem in more detail, and even better, provides a function that works:
Collapse
Copy Code
private int GetISO8601WeekNumber(DateTime date)
{
// Calculates the ISO 8601 Weeknumber
// In this scenario the first day of the week is monday,
// and the week rule states that:
// [...] the first calendar week of a year is the one
// that includes the first Thursday of that year and
// [...] the last calendar week of a calendar year is
// the week immediately preceding the first
// calendar week of the next year.
// The first week of the year may thus start in the
// preceding year
const int JAN = 1;
const int DEC = 12;
const int LASTDAYOFDEC = 31;
const int FIRSTDAYOFJAN = 1;
const int THURSDAY = 4;
bool Week53Flag = false;
// Get the day number since the beginning of the year
int DayOfYear = date.DayOfYear;
// Get the numeric weekday of the first day of the
// year (using sunday as FirstDay)
int StartWeekDayOfYear =
(int)(new DateTime(date.Year, JAN, FIRSTDAYOFJAN)).DayOfWeek;
int EndWeekDayOfYear =
(int)(new DateTime(date.Year, DEC, LASTDAYOFDEC)).DayOfWeek;
// Compensate for the fact that we are using monday
// as the first day of the week
if (m_calendar.m_dateTimeFormat.FirstDayOfWeek!=0)
{
//if( StartWeekDayOfYear == 0)
StartWeekDayOfYear = 8 - StartWeekDayOfYear;
//if( EndWeekDayOfYear == 0)
EndWeekDayOfYear = 8 - EndWeekDayOfYear;
}
// Calculate the number of days in the first and last week
int DaysInFirstWeek = 8 - (StartWeekDayOfYear );
int DaysInLastWeek = 8 - (EndWeekDayOfYear );
// If the year either starts or ends on a
// thursday it will have a 53rd week
if (StartWeekDayOfYear == THURSDAY ||
EndWeekDayOfYear == THURSDAY)
Week53Flag = true;
// We begin by calculating the number of FULL
// weeks between the start of the year and
// our date. The number is rounded up, so the
// smallest possible value is 0.
int FullWeeks =
(int) Math.Ceiling((DayOfYear - (DaysInFirstWeek))/7.0);
int WeekNumber = FullWeeks;
// If the first week of the year has at least four days,
// then the actual week number for our date
// can be incremented by one.
if (DaysInFirstWeek >= THURSDAY)
WeekNumber = WeekNumber +1;
// If week number is larger than week 52 (and the year
// doesn't either start or end on a thursday)
// then the correct week number is 1.
if (WeekNumber > 52 && !Week53Flag)
WeekNumber = 1;
// If week number is still 0, it means that we are trying
// to evaluate the week number for a
// week that belongs in the previous year (since that week
// has 3 days or less in our date's year).
// We therefore make a recursive call using the last day of
// the previous year.
if (WeekNumber == 0)
WeekNumber = GetISO8601WeekNumber(
new DateTime(date.Year-1, DEC, LASTDAYOFDEC));
return WeekNumber;
}
If you use the ISO8601 calendar (most of Europe),
MonthCalendar
will give you a correct week, if not, you will get the Microsoft week that might be right or wrong depending on your culture setting.
Using a callback to calculate week number
If you don't get the correct week, all hope is not lost, you can override the calendar's standard week routines and supply your own callback function that calculates the week numbers through the
WeeknumberCallback
property. The callback function must take a
DateTime
as the only parameter, and return an integer:
Collapse
Copy Code
public int GetWeek(DateTime dt)
{
// Calculate weeknumber here
}
If the above function is our callback, setting it up could look something like this:
Collapse
Copy Code
private void Form1_Load(object sender, System.EventArgs e)
{
monthCalendar1.WeeknumberCallBack =
new WeekCallBack(this.GetWeek);
}
Known problems/issues
- Since this control uses an
, it suffers from the infamous ImageList bug that destroys the alpha channel for 32 bit images when you add images to theImageList
in design mode. Workarounds for this could be to replace theImageList
with a control like theImageList
by Tom Guinter (that is available here), or to add the images at run time. This is, hopefully, fixed in Visual Studio 2005 so it might not be worth the hassle.ImageSet
Conclusion
I hope this control can be of use to you. I'm sure there is plenty of room for improvements and added functionality, so if you have any ideas or suggestions, please post a comment.