如何处理 DTN_FORMAT 通知

本主题演示如何处理日期和时间选取器 (DTP) 控件发送的格式通知。

需要了解的事项

技术

先决条件

  • C/C++
  • Windows 用户界面编程

说明

DTP 控件会发送 DTN_FORMAT 通知,以请求在控件的回调字段中显示文本。 应用程序必须处理该通知,以便让 DTP 控件能够显示其本身不支持的信息。

以下 C++ 代码示例是一个应用程序定义的函数 (DoFormat),它通过为回调字段提供文本字符串来处理 DTN_FORMAT 通知代码。 应用程序会调用 GetDayNum 应用程序定义的函数,以便请求在回调字符串中使用日期数字。

//  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. StringCchPrintf truncates the formatted string if
//  the entire string will not fit into the destination buffer. 

void WINAPI DoFormat(HWND hwndDP, LPNMDATETIMEFORMAT lpDTFormat)
{
HRESULT hr = StringCchPrintf(lpDTFormat->szDisplay,
                sizeof(lpDTFormat->szDisplay)/sizeof(lpDTFormat->szDisplay[0]),
                L"%d",GetDayNum(&lpDTFormat->st));
if(SUCCEEDED(hr))
 {
   // Insert code here to handle the case when the function succeeds.      
 }
else
 {
   // Insert code here to handle the case when the function fails or the string 
   // is truncated.
 }
}

GetDayNum 应用程序定义的函数

应用程序定义的示例函数 DoFormat 可调用以下 GetDayNum 应用程序定义的函数,以请求基于当前日期的日期数字。 GetDayNum 会返回一个从 0 到 366 的 INT 值,表示一年中的当前日期。 此该函数会在处理过程中调用另一个应用程序定义的函数 IsLeapYr

//  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);
}        

IsLeapYr 应用程序定义的函数

应用程序定义的函数 GetDayNum 会调用 IsLeapYr 函数来确定当前年份是否为闰年。 IsLeapYr 会返回一个 BOOL 值,如果是闰年,则该值为 TRUE,否则为 FALSE

//  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)
{
    BOOL fLeapYr = FALSE;

    // If the year is evenly divisible by 4 and not by 100, but is 
    // divisible by 400, it is a leap year.
    if ((!(iYear % 4))             // each even fourth year
            && ((iYear % 100)      // not each even 100 year
            || (!(iYear % 400))))  // but each even 400 year
        fLeapYr = TRUE;

    return (fLeapYr);
}        

使用日期和时间选取器控件

日期和时间选取器控件参考

日期和时间选取器