c# - 如何设置 DateTimePicker 下拉列表以仅选择年或月?

标签 c# .net winforms datetimepicker monthcalendar

就像 How can I set the datetimepicker dropdown to show Months only 中讨论的那样可以覆盖 DateTimePicker 来获取 MonthPicker

我已经阅读了很多网站,但不知道如何执行类似的操作来获取 YearPicker
也许有人可以帮忙。

最佳答案

此自定义控件对标准 DateTimePicker 进行了一些调整,以仅获得“年”或“月”选择样式。

▶ 标准 DateTimePicker 的 CustomFormat Format 属性已禁用,在内部将前者设置为 yyyyMMMM (简单修改即可添加不同格式)后者为DateTimePickerFormat.Custom 。这些属性在 PropertyGrid 中是隐藏的,无法更改。

▶ 浏览功能保留,但仅限十年/年或十年/年/月选择。
单击 DTP 的标题区域,会显示十年选择器,并且上一个和下一个按钮当然可以使用(这些按钮只能显示年份)。

▶ 当 MCN_VIEWCHANGE 出现时,DTP 关闭并设置当前值。通知显示,在 NMVIEWCHANGE 中传递当前选择级别结构,当前选择已达到 SelectionMode 设置的查看模式 属性(property)。
此属性值是一个枚举数,它反过来反射(reflect)了 MonthCalendar 的 MCM_SETCURRENTVIEW 消息值。

▶ 当前 View 设置为发送 MCM_SETCURRENTVIEW向 MonthCalendar 控件发送消息,将默认 View 更改为 MCMV_DECADE MCMV_YEAR (取决于当前的 SelectionMode )每次显示 MonthCalendar 控件时。然后保留打开动画。

▶ 唯一改变的样式是 MCS_NOTODAY ,设置在 OnHandleCreated方法。可随时开启/关闭,调用 ShowMonCalToday()方法。
此样式显示Today日期,位于 DateTimerPicker 的底部。单击时它会设置当前的“年”或“月”值。


它是这样工作的:

DateTimePicker Years Month Only

在 VisualStudio 2017 上测试。
.Net Framework 4.8(仅限)。

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

[DesignerCategory("Code")]
public class MonthYearPicker : DateTimePicker
{
    private string m_CustomFormat = "yyyy";
    private DateTimePickerFormat m_Format = DateTimePickerFormat.Custom;
    private SelectionViewMode m_SelectionMode = SelectionViewMode.Year;
    private bool m_ShowToday = false;
    private IntPtr hWndCal = IntPtr.Zero;

    public MonthYearPicker() {
        base.CustomFormat = m_CustomFormat;
        base.Format = m_Format;
    }

    [DefaultValue(SelectionViewMode.Year)]
    [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
    [Category("Appearance"), Description("Set the current selection mode to either Month or Year")]
    public SelectionViewMode SelectionMode {
        get => m_SelectionMode;
        set {
            if (value != m_SelectionMode) {
                m_SelectionMode = value;
                m_CustomFormat = m_SelectionMode == SelectionViewMode.Year ? "yyyy" : "MMMM";
                base.CustomFormat = m_CustomFormat;
            }
        }
    }

    [DefaultValue(false)]
    [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
    [Category("Appearance"), Description("Shows or hides \"Today\" date at the bottom of the Calendar Control")]
    public bool ShowToday {
        get => m_ShowToday;
        set {
            if (value != m_ShowToday) {
                m_ShowToday = value;
                ShowMonCalToday(m_ShowToday);
            }
        }
    }

    [DefaultValue("yyyy")]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    public new string CustomFormat {
        get => base.CustomFormat;
        set => base.CustomFormat = m_CustomFormat;
    }

    [DefaultValue(DateTimePickerFormat.Custom)]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    public new DateTimePickerFormat Format {
        get => base.Format;
        set => base.Format = m_Format;
    }

    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        ShowMonCalToday(m_ShowToday);
    }

    protected override void OnDropDown(EventArgs e)
    {
        hWndCal = SendMessage(this.Handle, DTM_GETMONTHCAL, 0, 0);
        if (hWndCal != IntPtr.Zero) {
            SendMessage(hWndCal, MCM_SETCURRENTVIEW, 0, (int)(MonCalStyles)m_SelectionMode);
        }
        base.OnDropDown(e);
    }

    private void ShowMonCalToday(bool show)
    {
        int styles = SendMessage(this.Handle, DTM_GETMCSTYLE, 0, 0).ToInt32();
        styles = show ? styles &~(int)MonCalStyles.MCS_NOTODAY : styles | (int)MonCalStyles.MCS_NOTODAY;
        SendMessage(this.Handle, DTM_SETMCSTYLE, 0, styles);
    }

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg) {
            case WM_NOTIFY:
                var nmh = (NMHDR)m.GetLParam(typeof(NMHDR));
                switch (nmh.code) {
                    case MCN_VIEWCHANGE:
                        var nmView = (NMVIEWCHANGE)m.GetLParam(typeof(NMVIEWCHANGE));
                        if (nmView.dwNewView < (MonCalView)m_SelectionMode) {
                            SendMessage(this.Handle, DTM_CLOSEMONTHCAL, 0, 0);
                        }
                        break;
                    default:
                        // NOP: Add more notifications handlers...
                        break;
                }
                break;
            default:
                // NOP: Add more message handlers...
                break;
        }
        base.WndProc(ref m);
    }

    public enum SelectionViewMode : int
    {
        Month = MonCalView.MCMV_YEAR,
        Year = MonCalView.MCMV_DECADE,
    }

    // Move to a NativeMethods class, eventually
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    internal static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

    internal const int WM_NOTIFY = 0x004E;
    internal const int MCN_VIEWCHANGE = -750;

    internal const int DTM_FIRST = 0x1000;
    internal const int DTM_GETMONTHCAL = DTM_FIRST + 8;
    internal const int DTM_SETMCSTYLE = DTM_FIRST + 11;
    internal const int DTM_GETMCSTYLE = DTM_FIRST + 12;
    internal const int DTM_CLOSEMONTHCAL = DTM_FIRST + 13;

    internal const int MCM_FIRST = 0x1000;
    internal const int MCM_GETCURRENTVIEW = MCM_FIRST + 22;
    internal const int MCM_SETCURRENTVIEW = MCM_FIRST + 32;

    [StructLayout(LayoutKind.Sequential)]
    internal struct NMHDR
    {
        public IntPtr hwndFrom;
        public UIntPtr idFrom;
        public int code;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct NMVIEWCHANGE
    {
        public NMHDR nmhdr;
        public MonCalView dwOldView;
        public MonCalView dwNewView;
    }

    internal enum MonCalView : int
    {
        MCMV_MONTH = 0,
        MCMV_YEAR = 1,
        MCMV_DECADE = 2,
        MCMV_CENTURY = 3
    }

    internal enum MonCalStyles : int
    {
        MCS_DAYSTATE = 0x0001,
        MCS_MULTISELECT = 0x0002,
        MCS_WEEKNUMBERS = 0x0004,
        MCS_NOTODAYCIRCLE = 0x0008,
        MCS_NOTODAY = 0x0010,
        MCS_NOTRAILINGDATES = 0x0040,
        MCS_SHORTDAYSOFWEEK = 0x0080,
        MCS_NOSELCHANGEONNAV = 0x0100
    }
}

关于c# - 如何设置 DateTimePicker 下拉列表以仅选择年或月?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61277364/

相关文章:

c# - 组合框显示成员问题,快把我逼疯了

c# - 无法更改 datagridview winforms 中的图像

c# - 在 View 中填充模型并将其传递给 Controller

c# - MVC 4 样式捆绑 - 如何添加浏览器特定的样式表

.net - 是否可以将 Windows Mobile 仿真构建到应用程序中?

C# 编译器在 C 中?

c# - 遍历数据中继器中所有行的最佳方法?

c# - 在 C# 中调用 Get-Smbshare

c# - 选择 WebClient 传出 IP

c# - 使用 DSL 生成 C# 代码