在DateTimePicker控件中更改周显示

在vb.net或C#应用程序的winforms环境中使用传统的DateTimePicker控件,我需要更改从正常的星期日到星期六到星期二到星期一显示星期的方式。我已经搜索了Google和Stack,却没有发现任何结果。创建自定义控件没有问题。我只是不知道从哪里开始。

评论
浅笑oo
浅笑oo

You can use SendMessage to send a MCM_SETFIRSTDAYOFWEEK message to the MonthCalendar of the DateTimePicker (read the notes related to this message in the Docs).

You first send a DTM_GETMONTHCAL message to get the handle of the MonthCalendar control. As shown, you can send this message in the DropDown event handler of the DateTimePicker.
If the handle is valid, set the first day sending MCM_SETFIRSTDAYOFWEEK. The lParam value determine the first day shown in the MonthCalendar:

0 = Monday, 1 = Tuesday etc.

If you want to build a custom control, you can use this one: it already shows how to deal with the DateTimePicker and its MonthCalendar dropdown, to change the current View and similar tasks.

internal const int DTM_FIRST = 0x1000;
internal const int DTM_GETMONTHCAL = DTM_FIRST + 8;
internal const int MCM_FIRST = 0x1000;
internal const int MCM_SETFIRSTDAYOFWEEK = MCM_FIRST + 15;

internal enum MCWeekDay : int 
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

internal void MonthCalendarSetFirstDayOfWeek(MCWeekDay weekDay)
{
    IntPtr hWndCal = SendMessage(dateTimePicker1.Handle, DTM_GETMONTHCAL, 0, 0);
    if (hWndCal != IntPtr.Zero) {
        SendMessage(hWndCal, MCM_SETFIRSTDAYOFWEEK, 0, (int)weekDay);
    }
}

private void dateTimePicker1_DropDown(object sender, EventArgs e)
{
    MonthCalendarSetFirstDayOfWeek(MCWeekDay.Tuesday);
}
点赞
评论