如何在自定义容器控件中触发 KeyDown 事件?
我有一个自定义容器控件(源自 FlowLayoutPanel
),其中包含零个或多个由用户拖动到那里的子控件。单击子控件时,它会被“选择”。 (它是用彩色边框绘制的,并且可以使用选项来更改其属性。)
我想处理 Delete
键,这样,如果用户当前正在容器控件中工作(在例如,在子控件上)当前选定的控件(如果有)将被删除。
我已经使用子项目上的右键单击上下文菜单来使用删除功能。我的问题是处理 Delete
键。我无法弄清楚如何在容器控件中引发 KeyDown 事件。我知道它与焦点有关,因此必须调用 Control.Select()
(或其等效项),但是最好的方法是什么?这个焦点逻辑位于哪里?或者有更好的方法吗?
我不想处理表单中的 KeyDown
事件,然后找出焦点在哪里。这是一个可重用的容器控件,我希望逻辑驻留在其中。
我需要做什么才能在自定义控件上触发 KeyDown
事件?
public class MyContainer : FlowLayoutPanel
{
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
MessageBox.Show("How do I get here?");
e.Handled = true;
}
base.OnKeyDown(e);
}
}
I have a custom container control (deriving from FlowLayoutPanel
) which contains zero or more child controls dragged there by the user. When a child control is clicked, it is "selected." (It is drawn with a colored border and options are available for altering its properties.)
I would like to handle the Delete
key so that, if the user is currently working in the container control (clicked within the control or on a child control, for instance) the currently selected control (if there is one) is deleted.
I already have the delete functionality working using a right-click context menu on the child items. My problem is handling the Delete
key. I cannot figure out how to get the KeyDown event to raise within my container control. I know it has something to do with focus, so that Control.Select()
(or its equivalent) must be called, but what is the best way to go about this? Where does this focus logic reside? Or is there a better way?
I do not want to handle the KeyDown
event in the form and then sniff out where the focus is. This is a reuseable container control and I want the logic to reside there.
What do I have to do to get the KeyDown
event to fire on a custom control?
public class MyContainer : FlowLayoutPanel
{
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
MessageBox.Show("How do I get here?");
e.Handled = true;
}
base.OnKeyDown(e);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MSDN 上将 KeyDown 事件列为对 FlowLayoutPanel 控件无意义。建议将 PreviewKeyDown 事件作为选择。
The KeyDown event is listed as unmeaningful for the FlowLayoutPanel control on MSDN. Suggest the PreviewKeyDown event as an alternative.
拖入容器的项目是否有可能正在接收该事件?
也许在将物品放入容器后,您需要手动将焦点设置到容器上。
Is it possible that the items dragged into the container are receiving the event?
Perhaps after an item is drug into your container, you need to manually set the focus to the container.