简体   繁体   中英

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

我想在c#的windows面板控件中获取keypress事件,对我来说是否有任何身体帮助......

You should handle the Panel.KeyPress event.

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

...

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

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.

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

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

I've created Panel overload:

public class PersoPanel : Panel

and used the overridden method 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);
}

Panel + Keypress - C# Discussion Boards - CodeProject

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM