0

我在弄清楚如何创建一个继承类来扩展 Windows 窗体控件以始终具有一个事件处理程序来处理该对象的每个实例的按键事件时遇到了一些麻烦。

我可能解释得不好。本质上,我想在 Windows 窗体中扩展 DatagridView 类,以便始终为我扩展的 DatagridView 类的任何实例化对象提供一个 keyPress 事件处理程序。

我想知道是否有可能有一个事件处理程序来监听按键并使用类似于我在下面编写的代码来处理它们:

    private void dgvObject_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsLetterOrDigit(e.KeyChar))
        {
            //start the loop at the currently selected row in the datagridview
            for (int i = dgvObject.SelectedRows[0].Index; i < dgvObject.Rows.Count; i++)
            {
                //will only evaluate to true when the current index has iterated above above the 
                //selected rows index number AND the key press event argument matches the first character of the current row
                // character of the 
                if (i > dgvObject.SelectedRows[0].Index && dgvObject.Rows[i].Cells[1].FormattedValue
                    .ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
                {
                    //selects current iteration as the selected row
                    dgvObject.Rows[i].Selected = true;
                    //scrolls datagridview to selected row
                    dgvObject.FirstDisplayedScrollingRowIndex = dgvObject.SelectedRows[0].Index;
                    //break out of loop as I want to select the first result that matches
                    break;
                }
            }
        }
    }

上面的代码只是选择下一行,该行以触发时 keypress 事件在其事件参数中的任何字符开头。我想知道我是否可以将其作为始终存在的继承处理程序的原因。我认为这比在我的 Windows 窗体中为每个单独的 DatagridView 对象显式创建数百个处理程序要好。如果我的想法是错误的,请随时纠正我!无论如何,感谢您的任何意见。

我已经用 C# 编程大约 5 个月了,我还在学习 =)

4

2 回答 2

3

是的,在你继承的类中只是 override OnKeyPress,你应该记得base.OnKeyPress之后调用:

protected override OnKeyPress(KeyPressEventArgs e)
{
   .. all your code

   base.OnKeyPress(e); // to ensure external event handlers are called
}
于 2012-12-17T11:32:04.397 回答
1

您可以通过覆盖 ProcessCmdKey 来捕获所有按键甚至组合:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{
    if (keyData == (Keys.Control | Keys.F)) 
    {
        //your code here
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
于 2012-12-17T11:35:29.663 回答