。NET DateTimePicker具有文本,但是我不知道如何获取和设置DateTimePicker的SelectionStart,SelectionLength和SelectionText属性。
例如,如何以编程方式选择日期“ 11/17/2001”中的2天数字?以及如何以编程方式确定当前选择的开始位置?
基本上,我想做的是下面的代码:
// Select the day's text
((TextBox)myDateTimePicker).SelectionStart = 3;
((TextBox)myDateTimePicker).SelectionLength = 2;
// Get the text start position
return ((TextBox)myDateTimePicker).SelectionStart;
以下代码是我的问题的答案。它源自DateTimePicker get focused field问题的answer。
public event System.EventHandler<EventArgs> Parent_ValueChanged;
public enum DatePart
{
YEAR,
MONTH,
DAY
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DatePart SelectedPart { get; set; }
private DateTime m_PreviousValue = TimeTools.UnixBaseTime;
private bool m_CheckSelectedPart = false;
public void DateTimeField_GotFocus(object sender, EventArgs e)
{
m_PreviousValue = this.Value;
m_CheckSelectedPart = true;
SendKeys.SendWait("{UP}");
SendKeys.SendWait("{DOWN}");
m_CheckSelectedPart = false;
}
public void DateTimeField_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Space:
e.IsInputKey = true;
break;
case Keys.Tab:
m_PreviousValue = this.Value;
m_CheckSelectedPart = true;
SendKeys.SendWait("{UP}");
SendKeys.SendWait("{DOWN}");
m_CheckSelectedPart = false;
// Set e.IsInputKey to false to let Windows use the Tab
// to go to the previous or next component with TabStop = true
if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
{
// false = exit to the left or up
e.IsInputKey = !(SelectedPart == DatePart.MONTH);
}
else
{
// false = exit to the right or down
e.IsInputKey = !(SelectedPart == DatePart.YEAR);
}
break;
default: break;
}
}
public void DateTimeField_KeyDown(object sender, KeyEventArgs e)
{
// Mimic Delphi's DateTimePicker behavior by advancing to the next part in the format
// using Space or Tab
if (e.KeyCode.Equals(Keys.Space) || e.KeyCode.Equals(Keys.Tab))
{
if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
{
SendKeys.Send("{left}");
}
else
{
SendKeys.Send("{right}");
}
}
}
private void DateTimeField_ValueChanged(object sender, EventArgs e)
{
if ((m_CheckSelectedPart) && (sender is DateTimePicker dtp))
{
TimeSpan change = (dtp.Value - m_PreviousValue);
var dayChange = Math.Abs(change.Days);
if (dayChange == 1)
{
SelectedPart = DatePart.DAY;
}
else if (dayChange >= 365)
{
SelectedPart = DatePart.YEAR;
}
else
{
SelectedPart = DatePart.MONTH;
}
m_PreviousValue = dtp.Value;
}
// parent's ValueChanged event handler
Parent_ValueChanged?.Invoke(sender, e);
}