将 KeyEvent 从窗体发送到控件
我有一个 Windows.Worms 应用程序。 在我的一个表单中,我显示了一个 DataGridView 及其关联的 ContextMenu(不是 ContextMenuStrip)。 ContextMenu 中的 MenuItem 定义了快捷方式。
这就是创建 ContextMenu 的方式:
Private _contextMenu As _
New ContextMenu( _
New MenuItem() { _
New MenuItem("Item A", AddressOf ItemA_Click, Shortcut.CtrlA) With {.DefaultItem = True}, _
New MenuItem("Item B", AddressOf ItemB_Click, Shortcut.CtrlB), _
New MenuItem("Item C", AddressOf ItemC_Click, Shortcut.CtrlC), _
...
}) _
With {.Name = "MyContextMenu"}
如果我的 DataGridView 具有焦点并且我按 Ctrl + A ItemA_Click 被调用。
现在我希望快捷方式适用于我的整个表单,即使 DataGridView 没有焦点。
相反的方法很简单,我只需将表单的 KeyPreview 设置为 true
即可。 但我想将事件传递给我的 DataGridView。
我尝试从 DataGridView 调用 OnKeyDown 和 OnKeyPress 方法,但两者似乎都不起作用。 我不知道,但我想 ContextMenu 会忽略 Key...Events 并连接到消息队列,但我不知道如何将 System.Windows.Forms.KeyEventArgs 转换为 Windows 消息。
只有两个想法:
- 聚焦 DataGridView 并使用 SendKeys 作为仅针对我尸体的解决方案。
- 我无法从 ContextMenu 中提取逻辑并使用 KeyPreview 或其他东西。 像这样。
I have a Windows.Worms application. In one of my forms I display a DataGridView with a ContextMenu (not ContextMenuStrip) associated to it. The MenuItems in the ContextMenu have Shortcuts defined.
This is how the ContextMenu is created:
Private _contextMenu As _
New ContextMenu( _
New MenuItem() { _
New MenuItem("Item A", AddressOf ItemA_Click, Shortcut.CtrlA) With {.DefaultItem = True}, _
New MenuItem("Item B", AddressOf ItemB_Click, Shortcut.CtrlB), _
New MenuItem("Item C", AddressOf ItemC_Click, Shortcut.CtrlC), _
...
}) _
With {.Name = "MyContextMenu"}
If my DataGridView has the focus and I press Ctrl + A ItemA_Click is called.
Now I want the Shortcut to work for my entire form, even if the DataGridView doesn't have the focus.
The reversed way would be easy, I just have to set KeyPreview of the Form to true
. But I want to pass the event down to my DataGridView.
I tried to call the OnKeyDown and OnKeyPress methods from the DataGridView, but both don't seem to work. I don't know it, but I suppose that the ContextMenu ignores the Key... Events and hooks up to the message queue, but I haven't got a clu how to convert my System.Windows.Forms.KeyEventArgs to windows messages.
Just two thinks:
- Focus the DataGridView and use SendKeys as a solution only over my dead body.
- I can't pull the logic out of the ContextMenu and use KeyPreview or smth. like this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您几乎已经弄清楚了 - 尝试将表单的 KeyPreview 设置为 true,然后自己捕获快捷键。 当您发现快捷键被按下时,调用适当的方法:
(抱歉,这是 C#,因为我更熟悉 C# 语法...)
I think you almost figured it out - try setting the form's KeyPreview to true and then catching the shortcut key yourself. When you catch the shortcut key being pressed, call the appropriate method:
(Sorry, this is C# as I'm more familiar with C# syntax...)