Date and Time Picker ControlsDate and Time Picker Controls*
*



Contents  *



Index  *Topic Contents
*Previous Topic: NMCOMBOBOXEX
*Next Topic: Date and Time Picker Control Reference

Date and Time Picker Controls


A date and time picker (DTP) control provides a simple and intuitive interface through which to exchange date and time information with a user. For example, with a DTP control you can ask the user to enter a date and then retrieve his or her selection with ease.

arrowy.gifAbout Date and Time Picker Controls

arrowy.gifUsing Date and Time Picker Controls

arrowy.gifDate and Time Picker Control Reference

About Date and Time Picker Controls

You can create a date and time picker control by calling the CreateWindowEx function and specifying DATETIMEPICK_CLASS as the window class. The class is registered when the date and time picker class is loaded from the common control dynamic-link library (DLL). Register this class by calling the InitCommonControlsEx function, while specifying the ICC_DATE_CLASSES bit flag in the accompanying INITCOMMONCONTROLSEX structure.

Note Date and time picker controls are implemented in version 4.70 and later of Comctl32.dll.

Date and Time Picker User Interface

The client area of a date and time picker (DTP) control displays date and time information and acts as the interface through which users modify the information. The control's display consists of fields that are defined by the control's format string. Additionally, the control will display a check box when the DTS_SHOWNONE style is in use.

Each field in the control displays a portion of the date and time information that the control stores internally. The user can click a field to set keyboard focus and then provide keyboard input to change the information represented by that field. The DTP control automatically updates internal information based on the user's input. The control recognizes the following as valid input.
Input Category Description
Arrow Keys The control accepts arrow keys to navigate the fields in the control and change values. The user can press the LEFT ARROW or RIGHT ARROW keys to move through the control. If the user attempts to move past the last field in a given direction, the keyboard focus "wraps around" to the field on the opposite side of the control. The UP ARROW and DOWN ARROW keys change values in the current field incrementally.
End and Home The control accepts the VK_END and VK_HOME virtual keys to change the value within the current field to its upper and lower limits, respectively.
Function Keys The F2 key activates edit mode. The F4 key causes the control to display a drop-down month calendar control (pressing ALT+DOWN ARROW does this as well).
Numbers The control accepts numeric input in two-character segments. If the value entered by the user is invalid (like setting the month to 14), the control rejects it and resets the display to the previous value.
Plus and Minus The control accepts the VK_ADD and VK_SUBTRACT virtual keys from the numeric keypad to increment and decrement the value in the current field.

DTP controls that do not use the DTS_UPDOWN style display an arrow button. If the user clicks this button, a month calendar control drops down. The user can select a specific date by clicking an area of the calendar.

Date and Time Picker Control Styles

Date and time picker (DTP) controls have several styles that determine a control's appearance and behavior. The control styles are specified when creating the control by including the desired control styles in the dwStyle parameter of the CreateWindowEx call. You can change DTP control styles after you have created the control. To retrieve or change the window style, use the GetWindowLong and SetWindowLong functions.

You can set the display format of the DTP control using styles. The control defaults to the DTS_SHORTDATEFORMAT style, which produces output like "4/19/96". The DTS_LONGDATEFORMAT style causes the control to display date information like "Friday, April 19, 1996". Using the DTS_TIMEFORMAT style causes the control to display the time instead of the date in a format such as "5:31:42 PM".

Format Strings

A date and time picker (DTP) control relies on a format string to determine how it will display fields of information. By default, a DTP control can display information in any of three preset formats. Also, you can customize a DTP control's display using custom format strings.

Custom format strings provide greater flexibility for your application. In a custom format string, you can specify the order in which the control will display fields of information or indicate specific callback fields. The format characters that comprise the format string define the DTP control's display and field layout.

Preset DTP display formats

A DTP control can display information fields in three preset formats or according to a custom format string. Although the preset formats are format strings, they are set using the following window styles.
Style Description
DTS_LONGDATEFORMAT The control displays the date in long format. The default format string for this style is defined by LOCALE_SLONGDATEFORMAT, which produces output like "Friday, April 19, 1996".
DTS_SHORTDATEFORMAT The control displays the date in short format, the default style setting. The default format string for this style is defined by LOCALE_SSHORTDATE, which produces output like "4/19/96".
DTS_TIMEFORMAT The control displays the time. The default format string for this style is defined by LOCALE_STIMEFORMAT, which produces output like "5:31:42 PM".

Custom format strings

You can customize the display of a date and time picker (DTP) control using custom format strings. DTP controls support specified format characters that you can combine to create a format string. To assign the format string to the DTP control, use the DTM_SETFORMAT message.

You can add body text to the format string. For example, if you want the control to display the current date with the format "Today is: 04:22:31 Tuesday Mar 23, 1996", the format string is "'Today is: 'hh':'m':'s ddddMMMdd', 'yyy".

Note that segments of nonformat characters in the preceding example are delimited by single quotation marks. Failure to surround body text in this way will result in unpredictable display by the DTP.

Format characters

Date and time picker (DTP) controls support the following format characters.
String FragmentDescription
"d" The one- or two-digit day.
"dd" The two-digit day. Single-digit day values are preceded by a zero.
"ddd" The three-character weekday abbreviation.
"dddd" The full weekday name.
"h" The one- or two-digit hour in 12-hour format.
"hh" The two-digit hour in 12-hour format. Single-digit values are preceded by a zero.
"H" The one- or two-digit hour in 24-hour format.
"HH" The two-digit hour in 24-hour format. Single-digit values are preceded by a zero.
"m" The one- or two-digit minute.
"mm" The two-digit minute. Single-digit values are preceded by a zero.
"M" The one- or two-digit month number.
"MM" The two-digit month number. Single-digit values are preceded by a zero.
"MMM" The three-character month abbreviation.
"MMMM" The full month name.
"t" The one-letter AM/PM abbreviation (that is, AM is displayed as "A").
"tt" The two-letter AM/PM abbreviation (that is, AM is displayed as "AM").
"X" The callback field. The control still uses the other valid format characters and queries the owner to fill in the "X" portion. So the owner must be prepared to handle the DTN_WMKEYDOWN, DTN_FORMAT, and DTN_FORMATQUERY notification messages. Multiple "X" characters can be used in series to signify unique callback fields.
"y" The one-digit year (that is, 1996 would be displayed as "6").
"yy" The last two digits of the year (that is, 1996 would be displayed as "96").
"yyy" The full year (that is, 1996 would be displayed as "1996").

Callback fields

In addition to the standard format characters that define date and time picker (DTP) fields, you can customize your output by specifying certain parts of a format string as callback fields. To declare a callback field, include one or more "X" characters (ASCII Code 88) anywhere in the body of the format string. Like other DTP control fields, callback fields are displayed in left-to-right order based on their location in the format string.

You can create callback fields that are unique to each other by repeating the "X" character. Thus, the format string "XXddddMMMdd', 'yyyXXX" contains two unique callback fields, "XX" and "XXX". Remember, callback fields are treated as valid fields, so your application must be prepared to handle DTN_WMKEYDOWN notification messages.

When the DTP control parses the format string and encounters a callback field, it sends DTN_FORMAT and DTN_FORMATQUERY notification messages. The callback field string is included with the notifications so the receiving application can determine which callback field is being queried. The owner of the control must respond to these notifications to ensure that the custom information is properly displayed.

Date and Time Picker Control Notification Messages

A date and time picker (DTP) control sends notification messages when it receives user input or processes and reacts to callback fields. The parent of the control receives these notification messages in the form of WM_NOTIFY messages.

The following notification messages are used with DTP controls.
Notification Description
DTN_CLOSEUP Indicates that the drop-down month calendar is about to be removed.
DTN_DATETIMECHANGE Signals a change within the DTP control.
DTN_DROPDOWN Indicates that the drop-down month calendar is about to be displayed.
DTN_FORMAT Requests text to display in a portion of the format string described as a callback field.
DTN_FORMATQUERY Requests information about the maximum allowable size of the text to be displayed in a callback field.
DTN_USERSTRING Signals the end of a user's edit operation within the control. This notification is sent only by DTP controls that use the DTS_APPCANPARSE style.
DTN_WMKEYDOWN Signals that the user has pressed a key in a callback field of the DTP control.

Using Date and Time Picker Controls

This section provides information and sample code for implementing a date and time picker control.

Creating a Date and Time Picker Control

To create a date and time picker (DTP) control, use the CreateWindowEx function, specifying DATETIMEPICK_CLASS as the window class. You must first register the window class by calling the InitCommonControlsEx function, while specifying the ICC_DATE_CLASSES bit in the accompanying INITCOMMONCONTROLSEX structure.

The following example creates a DTP control in an existing modeless dialog box. It uses the DTS_SHOWNONE style to allow the user to simulate deactivation of the date within the control.

//  CreateDatePick creates a DTP control within a dialog box.
//  Returns the handle to the new DTP control if successful, or NULL 
//  otherwise.
//
//    hwndMain - The handle to the main window.
//    g_hinst - global handle to the program instance.
HWND WINAPI CreateDatePick(hwndMain)
{
    HWND hwndDP = NULL;
    INITCOMMONCONTROLSEX icex;

    icex.dwSize = sizeof(icex);
    icex.dwICC = ICC_DATE_CLASSES;

    InitCommonControlsEx(&icex);

    hwndDlg = CreateDialog  (g_hinst,
                             MAKEINTRESOURCE(IDD_DIALOG1),
                             hwndMain,
                             DlgProc);

    if(hwnDlg)
        hwndDP = CreateWindowEx(0,
                             DATETIMEPICK_CLASS,
                             "DateTime",
                             WS_BORDER|WS_CHILD|WS_VISIBLE|DTS_SHOWNONE,
                             20,50,220,20,
                             hwndDlg,
                             NULL,
                             g_hinst,
                             NULL);
    return (hwndDP);
}

Processing Date and Time Picker Notifications

The following example processes the DTN_DATETIMECHANGE, DTN_FORMAT, DTN_FORMATQUERY, and DTN_WMKEYDOWN notifications by calling the DoDateTimeChange, DoFormatQuery, DoFormat, and DoWMKeydown application-defined functions.

Other topics in this chapter provide additional information on these notifications. See Supporting Callback Fields and Processing the DTN_DATETIMECHANGE Notification Message for additional information.

BOOL WINAPI DoNotify(HWND hwnd, WPARAM wParam, LPARAM lParam)
{
    LPNMHDR hdr = (LPNMHDR)lParam;

    switch(hdr->code){
        case DTN_DATETIMECHANGE:{
            LPNMDATETIMECHANGE lpChange = (LPNMDATETIMECHANGE)lParam;
            DoDateTimeChange(lpChange);
        }
        break;

        case DTN_FORMATQUERY:{
            LPNMDATETIMEFORMATQUERY lpDTFQuery = (LPNMDATETIMEFORMATQUERY)lParam;

            // Process DTN_FORMATQUERY to ensure that the control
            // displays callback information properly.
            DoFormatQuery(hdr->hwndFrom, lpDTFQuery);
        }
        break;

        case DTN_FORMAT:{
            LPNMDATETIMEFORMAT lpNMFormat = (LPNMDATETIMEFORMAT) lParam;

            // Process DTN_FORMAT to supply information about callback
            // fields (fields) in the DTP control.
            DoFormat(hdr->hwndFrom, lpNMFormat);
        }
        break;

        case DTN_WMKEYDOWN:{
            LPNMDATETIMEWMKEYDOWN lpDTKeystroke = 
                            (LPNMDATETIMEWMKEYDOWN)lParam;

            // Process DTN_WMKEYDOWN to respond to a user's keystroke in
            // a callback field.
            DoWMKeydown(hdr->hwndFrom, lpDTKeystroke);
        }
        break;
    }
    // All of the above notifications require the owner to return zero.
    return FALSE;
}

Processing the DTN_DATETIMECHANGE Notification

A date and time picker (DTP) control sends the DTN_DATETIMECHANGE message whenever a change occurs. This message will be generated if the user changes one of the fields in the control or changes the state of the control's check box (DTS_SHOWNONE only).

The following example is an application-defined function designed to update a static control within a dialog box. The text within the static control is changed to reflect the current state of the DTP control.

void WINAPI DoDateTimeChange(LPNMDATETIMECHANGE lpChange)
{
    // If the user has unchecked the DTP's check box, change the
    // text in a static control to show the appropriate message.
    //
    // g_hwndDlg - a program-global address of a dialog box.

    if(lpChange->dwFlags == GDT_NONE)
        SetDlgItemText(g_hwndDlg, IDC_STATUS, "Disabled");
    else
        SetDlgItemText(g_hwndDlg, IDC_STATUS, "Active");
}

Supporting Callback Fields in a DTP control

If you plan to use callback fields with the date and time picker (DTP) controls in your application, you must be prepared to handle DTN_FORMATQUERY, DTN_FORMAT, and DTN_WMKEYDOWN notification messages. For additional information about callback fields, see Callback fields.

This section contains information about how your application can process these notification messages. There are several examples of source code for application-defined functions. The following list shows notification messages with sample functions that process them.
Notification Message Sample Function
DTN_FORMATQUERY DoFormatQuery
DTN_FORMAT DoFormat
DTN_WMKEYDOWN DoWMKeydown

The DoFormatQuery application-defined function

A date and time picker (DTP) control sends a DTN_FORMATQUERY notification message to request information about the maximum possible size of a callback field within the control. Handling this message ensures that all fields are displayed properly. The following DoFormatQuery application-defined function processes the DTN_FORMATQUERY notification message by calculating the width of the widest possible string for a given callback field.

//
//  DoFormatQuery processes DTN_FORMATQUERY messages to ensure that the
//  DTP control displays callback fields properly.
//
void WINAPI DoFormatQuery(
 HWND hwndDP, 
 LPNMDATETIMEFORMATQUERY lpDTFQuery)
{
    HDC hdc;
    HFONT hFont, hOrigFont;

    //  Prepare the device context for GetTextExtentPoint32 call.
    hdc = GetDC(hwndDP);

    hFont = FORWARD_WM_GETFONT(hwndDP, SendMessage);

    if(!hFont)
        hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
    
    hOrigFont = SelectObject(hdc, hFont);
    
    // Check to see if this is the callback segment desired. If so,
    // use the longest text segment to determine the maximum 
    // width of the callback field, and then place the information into 
    // the NMDATETIMEFORMATQUERY structure.
    if(!lstrcmp("XX",lpDTFQuery->pszFormat))
    GetTextExtentPoint32 (hdc,
                          "366",  // widest date string
                          3,
                          &lpDTFQuery->szMax);
    
    // Reset the font in the device context; then release the context.
    SelectObject(hdc,hOrigFont);
    ReleaseDC(hwndDP, hdc);
}

The DoFormat application-defined function

A date and time picker (DTP) control sends the DTN_FORMAT notification to request text that will be displayed in a callback field of the control. By handling this notification message, you allow the DTP control to display information that it does not natively support.

The following DoFormat application-defined function processes DTN_FORMAT notification messages by providing a text string for a callback field. DoFormat calls the GetDayNum application-defined function to request the day number to be used in the callback string.

//  DoFormat processes DTN_FORMAT to provide the text for a callback
//  field in a DTP control. In this example, the callback field
//  contains a value for the day of year. The function calls the 
//  application-defined function GetDayNum (below) to retrieve
//  the correct value.
//
void WINAPI DoFormat(HWND hwndDP, LPNMDATETIMEFORMAT lpDTFormat)
{
    wsprintf(lpDTFormat->szDisplay,"%d",GetDayNum(&lpDTFormat->st));    
}

The GetDayNum application-defined function

The application-defined sample function DoFormat calls the following GetDayNum application-defined function to request the day number based on the current date. GetDayNum returns an INT value that represents the current day of the year, from 0 to 366. This function calls another application-defined function, IsLeapYr, during processing.

//
//  GetDayNum is an application-defined function that retrieves the 
//  correct day of year value based on the contents of a given 
//  SYSTEMTIME structure. This function calls the IsLeapYr function to 
//  check if the current year is a leap year. The function returns an 
//  integer value that represents the day of year.
//
int WINAPI GetDayNum(SYSTEMTIME *st)
{
    int iNormYearAccum[] = {31,59,90,120,151,181,
                            212,243,273,304,334,365};

    int iLeapYearAccum[] = {31,60,91,121,152,182,
                            213,244,274,305,335,366};
    int iDayNum;

    if(IsLeapYr(st->wYear))
        iDayNum=iLeapYearAccum[st->wMonth-2]+st->wDay;
    else
        iDayNum=iNormYearAccum[st->wMonth-2]+st->wDay;
        
    return (iDayNum);
}

The IsLeapYr application-defined function

The application-defined sample function GetDayNum calls the IsLeapYr function to determine whether the current year is a leap year. IsLeapYr returns a BOOL value that is TRUE if it is a leap year and FALSE otherwise.

//
//  IsLeapYr determines if a given year value is a leap year. The
//  function returns TRUE if the current year is a leap year, and 
//  FALSE otherwise.
//
BOOL WINAPI IsLeapYr(int iYear)
{
    int iQuotient;
    BOOL fLeapYr = FALSE;

    // If the year is evenly divisible by 4 and not by 100, then this 
    // is a leap year.
    if(!(iYear%4) && (iYear%100)) 
        fLeapYr = TRUE;
    else{
        // If the year is evenly divisible by 4 and 100, then check to
        // see if the quotient of year divided by 100 is also evenly 
        // divisible by 4. If it is, then this is a leap year.
        if(!(iYear%4) && !(iYear%100)){
            iQuotient = iYear/100;
            if(!(iQuotient%4)) fLeapYr = TRUE;
        }
    }
    return (fLeapYr);
}

The DoWMKeydown application-defined function

Date and time picker (DTP) controls send the DTN_WMKEYDOWN message to report that the user has typed input in a callback field. Handling this message allows you to emulate the same keyboard responses supported for standard DTP fields or provide custom responses. The following DoWMKeydown application-defined function provides an example of how DTN_WMKEYDOWN notifications can be handled.

//
//  DoWMKeydown increments or decrements the day of month according 
//  to user keyboard input.
//
void WINAPI DoWMKeydown(
 HWND hwndDP,
 LPNMDATETIMEWMKEYDOWN lpDTKeystroke)
{
    int delta =1;
    
    if(!lstrcmp(lpDTKeystroke->pszFormat,"XX")){
        switch(lpDTKeystroke->nVirtKey){
            case VK_DOWN:
            case VK_SUBTRACT:
                delta = -1;  // fall through

            case VK_UP:
            case VK_ADD:
                lpDTKeystroke->st.wDay += delta;
                break;
        }
    }
}

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.