Fire Form KeyPress event

萝らか妹 提交于 2019-11-27 05:28:47

You need to override the ProcessCmdKey method for your form. That's the only way you're going to be notified of key events that occur when child controls have the keyboard focus.

Sample code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // look for the expected key
    if (keyData == Keys.A)
    {
        // take some action
        MessageBox.Show("The A key was pressed");

        // eat the message to prevent it from being passed on
        return true;

        // (alternatively, return FALSE to allow the key event to be passed on)
    }

    // call the base class to handle other key events
    return base.ProcessCmdKey(ref msg, keyData);
}

As for why this.Focus() doesn't work, it's because a form can't have the focus by itself. A particular control has to have the focus, so when you set focus to the form, it actually sets the focus to the first control that can accept the focus that has the lowest TabIndex value. In this case, that's your button.

Try setting the Form's KeyPreview property to True.

Set keyPreview = true on main form

I would use one of the following:

  1. Set the TabIndex property of the button to 0.

  2. Set the IsDefault property of the button to true - So, It will be fired when pressing the ENTER key.

I had this same problem and I know this question was answered long ago, but my solution to this problem came from another stack overflow question in which my only button grabbed and kept focus. I accepted the users advice and created a button which couldn't get focus.

Maybe someone will find this useful:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace I2c_Programmer {
    class NoSelectButton : Button{

            public NoSelectButton() {

            SetStyle(ControlStyles.Selectable, false);

        }
    }
}

Go into your designer, where the button is created and switch out the new System...button with your new class "new NoSelectButton();"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!