我有一个 C# Windows 窗体控件,其 DateTimePicker 设置为仅显示时间(自定义格式 h:mm),我的用户几乎总是会单击上/下按钮来控制分钟。但是,默认情况下,控件会更新小时数。
我怎样才能让这些按钮默认控制分钟?
作为奖励,当分钟超过 60 时,是否可以让小时向前/向后滚动?
我有一个 C# Windows 窗体控件,其 DateTimePicker 设置为仅显示时间(自定义格式 h:mm),我的用户几乎总是会单击上/下按钮来控制分钟。但是,默认情况下,控件会更新小时数。
我怎样才能让这些按钮默认控制分钟?
作为奖励,当分钟超过 60 时,是否可以让小时向前/向后滚动?
当datetimePicker
得到Focus
然后你发送钥匙自动转到分钟部分的权利。
dateTimePicker1.GotFocus += new EventHandler(dateTimePicker1_GotFocus);
void dateTimePicker1_GotFocus(object sender, EventArgs e)
{
SendKeys.Send("{right}");
}
Edper 的回答是正确的,一旦获得焦点,它会自动设置 datetimepicker 来更新分钟。但是,当分钟超过 60 时,小时部分不会自动前进或回滚。
您需要为此处理 KeyDown 事件。
试试这个(我结合了 Edper 的回答)。
private void Form1_Load(object sender, EventArgs e)
{
dateTimePicker1.CustomFormat = "h:mm";
dateTimePicker1.MouseWheel += new MouseEventHandler(dateTimePicker1_MouseWheel);
dateTimePicker1.KeyDown += new KeyEventHandler(dateTimePicker1_KeyDown);
dateTimePicker1.GotFocus += new EventHandler(dateTimePicker1_GotFocus);
}
void dateTimePicker1_GotFocus(object sender, EventArgs e)
{
SendKeys.Send("{right}");
}
void dateTimePicker1_MouseWheel(object sender, MouseEventArgs e)
{
if(e.Delta > 0)
dateTimePicker1.Value = dateTimePicker1.Value.AddMinutes(1);
else
dateTimePicker1.Value = dateTimePicker1.Value.AddMinutes(-1);
}
void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 38)
{
dateTimePicker1.Value = dateTimePicker1.Value.AddMinutes(1);
e.SuppressKeyPress = true;
}
else if (e.KeyValue == 40)
{
dateTimePicker1.Value = dateTimePicker1.Value.AddMinutes(-1);
e.SuppressKeyPress = true;
}
}
您需要使用 datetimepicker 自定义 datetimepicker.create usercontrol 并处理 keydown 事件
DateTimePicker 只需通过切换小时和分钟中的哪一个具有焦点来响应右箭头键。这意味着,如果 DTP 失去焦点然后重新获得焦点,则焦点会回到数小时。您可以通过处理 DTP 然后重新实例化它来解决此问题,以便 SendKeys.Send("{right}") 始终从具有焦点的时间开始,但这可能会给您带来在哪里执行此操作的问题。
我认为通过以下方式解决了问题:
private bool GfChangeingNudValueByCode = false;
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (!GfChangeingNudValueByCode)
{
// Only do this when the user has changed the NUD's value not when this code
// changes it to zero at the end of this handler
if (numericUpDown1.Value == -1)
{
// The user has pressed the down arrow so decrement the DTP's value
dateTimePicker1.Value = dateTimePicker1.Value.AddMinutes(-1);
}
if (numericUpDown1.Value == 1)
{
// The user has pressed the up arrow so increment the DTP's value
dateTimePicker1.Value = dateTimePicker1.Value.AddMinutes(1);
}
// Reset the NUD's value to zero so that we can tell which arrow the user
// presses next but first set the flag to true otherwise we would get a
// stack-overflow when we set the NUD's value to zero which results in
// this event handler being re-entered and re-entered and re-entered ...
GfChangeingNudValueByCode = true;
numericUpDown1.Value = 0;
GfChangeingNudValueByCode = false;
}
}
这导致 DTP/NUD 组合看起来像 DTP,用户可以通过以下方式更改时间值:
优质教育基金