DatetimePicker焦点

时间:2013-08-28 03:05:59

标签: c# datagridview datetimepicker

我目前正在开发会计系统。作为一项要求,我需要设计与鼠标交互较少的系统。

我的问题在于datetimepicker。我在DataGridView上使用它。当用户输入一个单元格时,将显示日期时间,但它会给我一个随机焦点(日,月,年)。有时它专注于白天,有时是月份,有时是年份。

Datetimepicker是否暴露了它的焦点?或者我怎样才能永远设置为Day? (的 DD /月/年)

Focus on Day

Focus on Year

1 个答案:

答案 0 :(得分:0)

我不知道更好的解决方案,但这有效。如果我找到一个更好的,我会在这里更新。这个想法是recreate the handle of your DateTimePicker。这是代码:

bool suppressEnter = false;
//Here is the Enter event handler used for all the DateTimePicker yours
private void dateTimePickers_Enter(object sender, EventArgs e){
  if (suppressEnter) return;
  DateTimePicker picker = sender as DateTimePicker;
  picker.Hide();
  typeof(DateTimePicker).GetMethod("RecreateHandle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(picker, null);
  picker.Show();
  suppressEnter = true;
  picker.Focus();
  suppressEnter = false;
}

上面的代码只是一个不使用win32的技巧。目的是在创建DateTimePicker的句柄时防止闪烁。我们可以使用SendMessage发送消息WM_SETREDRAW来抑制控件的绘制。通常我们有BeginUpdate()EndUpdate(),但我在DateTimePicker上找不到这些方法。这段代码会更简洁,而不是hacky:

[DllImport("user32")]
private static extern int SendMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);
private void dateTimePickers_Enter(object sender, EventArgs e){
   DateTimePicker picker = sender as DateTimePicker;
   //WM_SETREDRAW = 0xb
   SendMessage(picker.Handle, 0xb, new IntPtr(0), IntPtr.Zero);//BeginUpdate()
   typeof(DateTimePicker).GetMethod("RecreateHandle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(picker, null);
   SendMessage(picker.Handle, 0xb, new IntPtr(1), IntPtr.Zero);//EndUpdate()
}