如何以编程方式打开DateTimePicker C#控件?我想通过向控件发送密钥来显示Datetime Picker控件中的Calendar.有没有办法可以做到这一点?
请尝试以下方法
//part of the usings
using System.Runtime.InteropServices;
//declares
[DllImport("user32.dll")]
private static extern bool PostMessage(
IntPtr hWnd, // handle to destination window
Int32 msg, // message
Int32 wParam, // first message parameter
Int32 lParam // second message parameter
);
const Int32 WM_LBUTTONDOWN = 0x0201;
//method to call dropdown
private void button1_Click(object sender, EventArgs e)
{
Int32 x = dateTimePicker1.Width - 10;
Int32 y = dateTimePicker1.Height / 2;
Int32 lParam = x + y * 0x00010000;
PostMessage(dateTimePicker1.Handle, WM_LBUTTONDOWN, 1,lParam);
}
Run Code Online (Sandbox Code Playgroud)
在我的系统(Windows 7、.NET 35)上,其他解决方案不起作用。我在 MS 讨论网站上找到了另一个可行的解决方案。
using System.Runtime.InteropServices;
public static class Extensions
{
[DllImport("user32.dll", SetLastError = true)]
private static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
private const uint WM_SYSKEYDOWN = 0x104;
public static void Open(this DateTimePicker obj)
{
SendMessage(obj.Handle, WM_SYSKEYDOWN, (int)Keys.Down, 0);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
dateTimePicker1.Open();
Run Code Online (Sandbox Code Playgroud)
警告。dateTimePicker1如果它是一个控件DataGridView(即,如果您尝试在 DGV 上制作弹出日期选择器),则此操作将不起作用。如果将控件添加到其中,它确实可以工作Form。将会发生的情况是,合成的光标“向下”事件将被 DGV 吞没,并将当前单元格指针向下移动一位,而不是拖放 DTP 的日历。