You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程展开VB.NET中的DateTimePicker下拉日历?

解决方案

要让动态创建的DateTimePicker显示时自动展开下拉日历,需要借助Windows API发送消息模拟点击下拉按钮的操作——.NET WinForms的DateTimePicker控件没有直接提供展开日历的公开方法。

步骤1:声明Windows API函数和常量

在窗体类的顶部(所有方法之外)添加以下API声明:

Imports System.Runtime.InteropServices

Public Class YourFormName
    ' 声明SendMessage函数
    <DllImport("user32.dll", CharSet:=CharSet.Auto)>
    Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
    End Function

    ' DateTimePicker下拉日历的消息常量
    Private Const DTM_DROPDOWN As Integer = &H1000 + 1

步骤2:修改TextBox点击事件代码

在原有的创建并添加DateTimePicker的代码之后,添加发送消息的逻辑:

Private Sub TextBox1_Click(sender As Object, e As EventArgs) Handles TextBox1.Click
    Dim dtm = New System.Windows.Forms.DateTimePicker()
    With dtm
        .Font = New System.Drawing.Font("Comic Sans MS", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        .Format = System.Windows.Forms.DateTimePickerFormat.Custom
        .Location = New System.Drawing.Point(153, 237)
        .Size = New System.Drawing.Size(173, 35)
        ' 可选:绑定日期选择事件,选完后把值赋给TextBox并清理控件
        AddHandler dtm.CloseUp, AddressOf Dtm_CloseUp
    End With

    Me.GroupBox1.Controls.Add(dtm)
    dtm.Show()
    dtm.Focus() ' 先让控件获得焦点,确保消息能生效

    ' 发送消息展开下拉日历
    SendMessage(dtm.Handle, DTM_DROPDOWN, IntPtr.Zero, IntPtr.Zero)
End Sub

' 可选的CloseUp事件处理:用户选完日期后的操作
Private Sub Dtm_CloseUp(sender As Object, e As EventArgs)
    Dim picker = DirectCast(sender, DateTimePicker)
    ' 将选中的日期赋值给TextBox
    TextBox1.Text = picker.Value.ToString("yyyy-MM-dd")
    ' 移除并销毁DateTimePicker控件
    Me.GroupBox1.Controls.Remove(picker)
    picker.Dispose()
End Sub

说明

  • DTM_DROPDOWN是Windows系统定义的DateTimePicker控件消息,发送该消息会触发控件展开下拉日历。
  • 调用dtm.Focus()是为了确保控件处于激活状态,避免消息发送失败。
  • 可选的CloseUp事件处理可以在用户选择日期后自动将值回填到TextBox,并清理动态创建的DateTimePicker,提升用户体验。

内容的提问来源于stack exchange,提问作者Unis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 11:54:04