How to completely disable use of Arrow Keys in a ComboBox (the easy way).
A very powerful feature in .NET is the ability to create custom Components by inheritance that modify the
behavior and functionality of existing Controls. In the case of the built-in Microsoft Controls you can simply create a new Component and make it inherit from an existing Control.
How is inheriting from a Component different from a UserControl: a Component uses the existing user-interface of the existing Control it inherits from, a UserControl requires you design a user-interface.
Note that Components can also be used to define Controls that have no user-interface but which provide behavior and functionality to a WinForm; the Timer Control is an example of this type of Component.
A UserControl lets you create a compound Control by drag-dropping other Controls into its design-time surface, or creating and adding them in code. While (strangely enough) Visual Studio does allow you to drag-drop Controls onto the "blank" design-view of a Component, I have yet to see a case where there is an organic need for this, and, in the case of inheriting from something like a ComboBox, you would just waste your time doing this as well as create a bizarre non-feature.
1. Create a new Component:
Visual Studio / Project / Add Component => ComboBoxNoArrowKeys.cs => save
2. Open the code window for the new Component, clear it, and paste in this code:
using System.ComponentModel;
using System.Windows.Forms;
namespace YourNameSpace
{
public partial class ComboBoxNoArrowKeys : ComboBox
{
public ComboBoxNoArrowKeys()
{
InitializeComponent();
}
public ComboBoxNoArrowKeys(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public bool DisableArrowKeys { set; get; }
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if(DisableArrowKeys)
{
switch (keyData)
{
case Keys.Up:
case Keys.Down:
case Keys.Left:
case Keys.Right:
return true;
default:
break;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
}
Note there's a Public Proerty that implements a boolean flag here that Controls whether Arrow Keys are enabled or disabled, and I've set it to 'true by default. You can change that in your run-time code, or at design-time as you wish.