The method to cancel the focus control of the directional key in C is solved

  • 2020-05-12 03:06:56
  • OfStack

In the C# winform application, "KeyPress", "KeyUp", and "KeyDown" events are often used for keyboard response events, and can handle custom handling events for a particular key. Sometimes when you want to define a custom handling event for the arrow key, you can see that the custom handling event responds, but you can also see that the focus of the control on the form changes when you press the arrow key. This result is not what we want. We don't want to switch the focus of the control when we press the arrow key. We just want to respond to our custom handler. The following method can remove the direction key from the control focus:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)// The control that disables the focus of the directional key on the control handles the directional key handlers with its own custom functions 
        {
            switch (keyData)
            {
                case Keys.Up:
                    UpKey();
                    return true;// No further processing 
                case Keys.Down:
                    DownKey();
                    return true;
                case Keys.Left:
                    LeftKey();
                    return true;
                case Keys.Right:
                    RightKey();
                    return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

UpKey(), DownKey(), LeftKey(), and RightKey() are custom directional key handlers, respectively. After each custom handler, return true is used to indicate that the response to the key is not processed and is returned directly, thus avoiding the directional key controlling the focus of the control. For other keys, return base. ProcessCmdKey(ref msg, keyData); Use the default processing.

Related articles: