MouseDown 事件在 DateTimePicker 的 MonthCalendar 控件更新为当前 DateTime 值后引发。
如果在打开 MonthCalendar 的 Button 上生成了 MouseDown 事件。
单击控件的日期部分不会打开 MonthCalendar。
我建议不要使用 MouseDown 事件来更新 DateTimePicker 的值,因为这将导致用户每次单击控件上的任何位置时重置日期。这可能会令人不安(这取决于您)。
您可以改用DropDown 事件:仅当用户单击向下箭头按钮时才会引发该事件。
▶ 您不能将ValueChanged 事件与此处显示的代码一起使用:这可能会导致死锁(鉴于所涉及的 Win32 控件的性质和 SendMessage 的使用,这种死锁类型可能会传播到整个系统,所以,不要)。
这里的DtpUpdateMonthCalendardDate() 方法向作为参数传递的DateTimePicker 发送DTM_GETMONTHCAL 消息。
如果成功获取了 MonthCalendar 的句柄,则它会向 MonthCalendar 控件发送MCM_SETCURSEL 消息,以将其日期与父 DateTimePicker 的日期对齐。
新的 Date 使用 SYSTEMTIME 结构传递,该结构使用 DateTimePicker 的值初始化。
Private Sub dtpReceiveDate_DropDown(sender As Object, e As EventArgs) Handles dtpReceiveDate.DropDown
dtpReceiveDate.Value = Date.Today
' If result is False, something went wrong and the Date is not set
Dim result = DtpUpdateMonthCalendardDate(dtpReceiveDate)
End Sub
Private Function DtpUpdateMonthCalendardDate(dtp As DateTimePicker) As Boolean
If Not dtp.IsHandleCreated OrElse dtp.ShowUpDown Then Return False
Dim hWndCal = SendMessage(dtp.Handle, DTM_GETMONTHCAL, 0, 0)
If hWndCal = IntPtr.Zero Then Return False
Dim sysTime = New SYSTEMTIME(dtp.Value)
Return SendMessage(hWndCal, MCM_SETCURSEL, 0, sysTime) <> 0
End Function
Win32 声明:
Friend Const DTM_FIRST As Integer = &H1000
Friend Const DTM_GETMONTHCAL As Integer = DTM_FIRST + 8
Friend Const MCM_FIRST As Integer = &H1000
Friend Const MCM_GETCURSEL As Integer = MCM_FIRST + 1
Friend Const MCM_SETCURSEL As Integer = MCM_FIRST + 2
<StructLayout(LayoutKind.Sequential)>
Friend Structure SYSTEMTIME
Public Year As Short
Public Month As Short
Public DayOfWeek As Short
Public Day As Short
Public Hour As Short
Public Minute As Short
Public Second As Short
Public Milliseconds As Short
Public Sub New(dt As Date)
Year = CShort(dt.Year)
Month = CShort(dt.Month)
DayOfWeek = CShort(dt.DayOfWeek)
Day = CShort(dt.Day)
Hour = CShort(dt.Hour)
Minute = CShort(dt.Minute)
Second = CShort(dt.Second)
Milliseconds = CShort(dt.Millisecond)
End Sub
Public Function ToDateTime() As Date
Return New DateTime(Year, Month, Day, Hour, Minute, Second, Milliseconds)
End Function
End Structure
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Friend Shared Function SendMessage(hWnd As IntPtr, Msg As Integer, wParam As Integer, lParam As Integer) As IntPtr
End Function
<DllImport("User32", SetLastError:=True, CharSet:=CharSet.Auto)>
Friend Shared Function SendMessage(hWnd As IntPtr, msg As Integer, wParam As Integer, lParam As SYSTEMTIME) As Integer
End Function