如何在 C# 中的 Windows 面板控件中获取按键事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2132130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:44:29  来源:igfitidea点击:

How to get Keypress event in Windows Panel control in C#

c#winformseventskeypress

提问by ratty

i want to get keypress event in windows panel control in c#, is any body help for me...

我想在 c# 中的 Windows 面板控件中获取按键事件,对我有任何帮助...

采纳答案by James

You should handle the Panel.KeyPressevent.

您应该处理Panel.KeyPress事件。

Example

例子

public void MyKeyPressEventHandler(Object sender, KeyPressEventArgs e)
{
    ... do something when key is pressed.
}

...

(MyPanel as Control).KeyPress += new KeyPressEventHandler(MyKeyPressEventHandler);

回答by Oliver

The problem is, that at first your main form got the KeyPress and will immediately send this message to the active control. If that doesn't handle this key press it will be bubbled up to the parent control and so on.

问题是,一开始你的主窗体得到了 KeyPress,并会立即将此消息发送到活动控件。如果这不能处理这个按键,它将冒泡到父控件等等。

To intercept this chain, you have to in your Form.KeyPreviewto trueand add an handler to Form.KeyPress. Now you can handle the pressed key within your form.

要拦截这个链,你必须在你的Form.KeyPreviewto 中true添加一个处理程序到Form.KeyPress. 现在您可以在表单中处理按下的键。

回答by Picsdonald

"Panel" objects cannot receive the "KeyPress" event correctly.

“面板”对象无法正确接收“KeyPress”事件。

I've created Paneloverload:

我创建了Panel重载:

public class PersoPanel : Panel

and used the overridden method ProcessCmdKey:

并使用了重写的方法ProcessCmdKey

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)

to intercept pressed keys:

拦截按下的键:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    MessageBox.Show("You press " + keyData.ToString());

    // dO operations here...

    return base.ProcessCmdKey(ref msg, keyData);
}

回答by ratty

Panel + Keypress - C# Discussion Boards - CodeProject

面板 + 按键 - C# 讨论板 - CodeProject

http://www.codeproject.com/Messages/704386/Panel-plus-Keypress.aspx

http://www.codeproject.com/Messages/704386/Panel-plus-Keypress.aspx