C#DateTimePicker得到焦点字段

时间:2016-07-14 21:24:33

标签: c# winforms datetimepicker

我试图确定在DateTimePicker(WinForms)应用程序中选择(突出显示)了哪个控件(天,月,年)。是否有属性,表明选择了哪个控件?如果是这样,我可以通过编程方式从另一个控件中更改控件值吗?

有没有办法集中控制DateTimePicker

1 个答案:

答案 0 :(得分:2)

简短回答:不,不容易。

DateTimePicker基本上是SysDateTimePick32的包装器,并且在ShowUpDown设置为true时,不会公开任何易于使用的属性来确定选择了哪个子窗口。它在其源代码中甚至没有私有成员 - 它基本上只是将内容转发给底层的com控件,ala UnsafeNativeMethods.SendMessage

一种方法是向上发送然后向下发送并检查哪个部分发生了变化。这是一个样本。创建一个新的winforms应用程序,然后添加DateTimePicker,Label和Button。之后,在using语句之后将下面的代码复制到form1.cs中:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public enum DatePart
        {
            YEAR,
            MONTH,
            DAY
        }

        public DatePart part { get; set; }
        private DateTime previous { get; set; }
        private bool checkSelectedPart { get; set; }


        public Form1()
        {
            InitializeComponent();


            dateTimePicker1.ValueChanged += DateTimePicker1_ValueChanged;
            dateTimePicker1.KeyPress += DateTimePicker1_KeyPress;
            previous = dateTimePicker1.Value;

        }

        private void DateTimePicker1_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            if (checkSelectedPart)
            {
                var dtp = sender as DateTimePicker;
                TimeSpan change = (dtp.Value - previous);
                var dayChange = Math.Abs(change.Days);
                if (dayChange == 1)
                    part = DatePart.DAY;
                else if (dayChange >= 365)
                    part = DatePart.YEAR;
                else
                    part = DatePart.MONTH;

                previous = dtp.Value;

                label1.Text = part.ToString();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            checkSelectedPart = true;
            dateTimePicker1.Focus();
            SendKeys.SendWait("{UP}");
            SendKeys.SendWait("{DOWN}");
            checkSelectedPart = false;
            button1.Focus();
        }
    }
}