Click here to Skip to main content

ExtendedDateTimePicker control with week numbers

Sample screenshot


My mission was to find a DateTimePicker control supporting week numbers. This was not as easy as I'd expected it to be...

After having Googled all day (almost), and obviously not finding any code here at The Code Project, I found a bit of VB code that helped me further... However, as all my components are written in C#, I started "translating" it. This article simply enlists the code in C#. The original VB code under the original article "Displaying week numbers in a DateTimePicker control's dropdown part" by Herfried K. Wagnercan, can be found here.


Feel free to report any errors or further thoughts about the code! The code lacks comments, but is quite self-explanatory for an intermediate programmer with some experience of Win32.

The Code

using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsApplication3
    public class ExtendedDateTimePicker : DateTimePicker
        private static extern int GetWindowLong(IntPtr h, int index);

        private static extern int SetWindowLong(IntPtr h, int index, int value);

        private const int GWL_STYLE = (-16);
        private const int MCM_FIRST = 0x1000;
        private const int MCM_GETMINREQRECT = (MCM_FIRST + 9);
        private const int MCS_WEEKNUMBERS = 0x4;
        private const int DTM_FIRST = 0x1000;
        private const int DTM_GETMONTHCAL = (DTM_FIRST + 8);

        private static extern IntPtr SendMessage(IntPtr h, 
                       int msg, int param, int data);

        private static extern int SendMessage(IntPtr h, int msg, 
                       int param, ref Rectangle data);

        private static extern int MoveWindow(IntPtr h, int x, int y, 
                       int width, int height, bool repaint);

        private bool m_ShowWeekNumbers;

        [Browsable(true), DesignerSerializationVisibility(
        public bool ShowWeekNumbers
                return m_ShowWeekNumbers;
                m_ShowWeekNumbers = value;

        protected override void OnDropDown(EventArgs e)
            IntPtr monthView = SendMessage(Handle, DTM_GETMONTHCAL, 0, 0);
            int style = GetWindowLong(monthView, GWL_STYLE);
            if (ShowWeekNumbers)
                style = style | MCS_WEEKNUMBERS;
                style = style & ~MCS_WEEKNUMBERS;
            Rectangle rect = new Rectangle();
            SetWindowLong(monthView, GWL_STYLE, style);
            SendMessage(monthView, MCM_GETMINREQRECT, 0, ref rect);
            MoveWindow(monthView, 0, 0, rect.Right + 2, rect.Bottom, true);

Web03 | 2.8.160204.4 | Advertise | Privacy
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service