如何在DateTimePicker中设置字体大小

4

我想在C#窗体中的DateTimePicker控件中增加字体大小。我想把DateTimePicker中的最小字体大小设置为14到16。

我尝试了下面的代码,但它没有起作用。

dateTimePicker1.CalendarFont = new Font("Courier New", 8.25F, FontStyle.Italic, GraphicsUnit.Point, ((Byte)(0)));

欢迎来到SO!请在适用的情况下始终使用语言标签,如C#,并避免使用非常通用的标签,如“size”和“set”,除非它们是基本的。 - Ciro Santilli OurBigBook.com
字体大小由用户选择的视觉样式主题固定。您需要在Main方法中删除Application.EnableVisualStyles();语句。通常就是这样结束了。 - Hans Passant
可能是重复的问题: https://dev59.com/UnDYa4cB1Zd3GeqPGf1T - Shachaf.Gortler
3个回答

6
如果您希望保留应用程序中其他控件的视觉样式,但仅禁用日期选择器的下拉菜单,则可以使用以下代码:
public class MyDateTimePicker : DateTimePicker
{
    [DllImport("uxtheme.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
    static extern Int32 SetWindowTheme(IntPtr hWnd, String textSubAppName, String textSubIdList);

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

    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr GetParent(IntPtr hWnd);

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    protected override void OnDropDown(EventArgs eventargs)
    {
        if (Application.RenderWithVisualStyles)
        {
            const int DTM_GETMONTHCAL = 0x1008;

            //Get handle of calendar control - disable theming
            IntPtr hCalendar = SendMessage(this.Handle, DTM_GETMONTHCAL, IntPtr.Zero, IntPtr.Zero);
            if (hCalendar != IntPtr.Zero)
            {
                SetWindowTheme(hCalendar, "", "");

                //Get handle of parent popup - resize appropriately
                IntPtr hParent = GetParent(hCalendar);
                if (hParent != IntPtr.Zero)
                {
                    //The size you specify here will depend on the CalendarFont size chosen
                    MoveWindow(hParent, 0, 0, 400, 300, true);
                }
            }
        }

        base.OnDropDown(eventargs);
    }
}

这个很棒 - 比起其他建议的解决方案,整个应用程序都舍弃视觉样式要好得多。 - edhubbell

-1
在iOS中,您需要创建一个渲染器:
private void SetFont(CustomPicker view)
{
    UIFont uiFont;
    Control.Font = UIFont.SystemFontOfSize(11f); //the size which u want

}

在安卓中,您必须为渲染器设置字体:
private void SetFont(CustomDatePicker view)
{
    if (view.Font != Font.Default) 
    {
        Control.TextSize = view.Font.ToScaledPixel();
        Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets,"Roboto-Bold.ttf");
        Control.Typeface = font;
        Control.Typeface = view.Font.ToTypeface();
    }
}

-1
在主程序中删除/注释掉以下代码行:Application.EnableVisualStyles(); 然后在您的代码后面添加新的代码行:
dateTimePicker1.Font = new Font("Courier New", 8.25F, FontStyle.Italic, GraphicsUnit.Point, ((Byte)(0)));

1
注意!!!注释掉Application.EnableVisualStyles()可能会导致一些不良的视觉效果!!!在直接应用之前,请先查看以下链接:https://dev59.com/uWw15IYBdhLWcg3wMo8Y - curiousBoy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接