Introduction
I was looking on this site to find a way to make a read only ComboBox
. There is more than one article to do that, but some of them are very huge and some do not work, especially against Delete button. That made me look for a solution for this problem. Finally, I found a very simple way to do that. The idea is to control the input keys.
There are two types of input keys:
- Normal keys (letters, numbers…)
- Control keys (delete, left…)
Using the Code
The simplest way to control a Normal key is by converting it to null before using it. To do that, we can handle the input keys for the combo box by using: KeyPress
event (or simply disable this event), see the code. And now, a slightly harder step, controlling the control keys. First, let us watch the key pressed before doing its work, if it is a control key, we will not pass it to do as an underline control. To do that, the best way is to use the KeyDown
Event.
My ComboBox
allows: Cntr+C(copy) and arrows effects. Finally we will create contextMenuStrip
to allow only copy, as shown below:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys)Shortcut.CtrlC)
{
Clipboard.SetData(DataFormats.Text, comboBox1.SelectedText);
}
else if (e.KeyData == Keys.Left || e.KeyData == Keys.Right ||
e.KeyData == Keys.Up || e.KeyData == Keys.Down) { }
else
{
e.Handled = true;
}
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
Clipboard.SetData(DataFormats.Text, comboBox1.SelectedText );
}
And now you can improve your code as you wish. You can also add your own features. If you have any questions, please post them.
Hints
- You can change the style of
combobox
to list style. (See the code.) But, doing that may remove some features (copy, select text, … ), your choice depends on your application.
private void Form1_Load(object sender, EventArgs e)
{
comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;
}
- If someone wants to delete
contextMenuStrip
effect "Mouse right-click", you can add the following:
private void Form1_Load(object sender, EventArgs e)
{
comboBox3.ContextMenu = new ContextMenu();
}