C#发送按键到DataGridViewCell

时间:2010-09-02 20:30:27

标签: c# winforms datagridview sendkeys

我的DataGridView中有一个DateTimePicker单元格。我希望能够进入编辑模式并在单击按钮时删除日历。我能够毫无困难地完成第一部分,但第二部分不起作用。如果我有一个独立的DateTimePicker,SendKeys调用确实按预期工作。

//Select the cell and enter edit mode -  works
myDGV.CurrentCell = myDGV[calColumn.Index, e.RowIndex];
myDGV.BeginEdit(true);

//Send an ALt-Down keystroke to drop the calendar  - doesn't work
SendKeys.SendWait("%{DOWN}");

从调试开始我认为问题在于键击被发送到DGV而不是我正在尝试编辑的特定单元格。我认为的原因是我已经将代码放入由网格KeyPress和KeyDown事件接收的日志密钥。他们记录我在网格上的箭头和SendKeys发送的密钥,但不是那些我在编辑单元格时输入的密码。

2 个答案:

答案 0 :(得分:1)

请在C# Winforms DataGridView Time Column上查看我的回答。我相信它会完美地满足您的需求。您也可以将它用于具有ComboBox的列。

答案 1 :(得分:0)

我最近重新讨论了这个问题,因为0A0D提供的实现并不总是与网格的键盘导航(箭头/标签)很好地配合。有时可以绕过DateTimePicker并在DataGridViewTextBoxCell中输入文字。这导致我的验证逻辑吓坏了;并且在未能找到防止滑动发生的方法后,我决定尝试再次使用自定义列。

修复结果非常简单。我创建了一个扩展DateTimePicker,其方法是发送显示日历所需的击键。

/// <summary>
/// Extended DateTimePicker with a method to programmatically display the calendar.
/// </summary>
class DateTimePickerEx : DateTimePicker
{
    [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;

    /// <summary>
    /// Displays the calendar input control.
    /// </summary>
    public void ShowCalendar()
    {
        Int32 x = Width - 10;
        Int32 y = Height / 2;
        Int32 lParam = x + y * 0x00010000;

        PostMessage(Handle, WM_LBUTTONDOWN, 1, lParam);
    }
}

然后,我修改了MSDN DateTime column example,使CalendarEditingControl继承自DateTimePickerEx

然后在托管DataGridView的表单中,我使用EditingControl属性来调用ShowCalendar()方法。

DateTimePickerEx dtp = myDataGridView.EditingControl as DateTimePickerEx;
if (dtp != null)
    dtp.ShowCalendar();
相关问题