Reputation: 5098
Is there a way to disable value change for a combo box without graying it out in windows forms? I saw a few posts but they were for WPF and didnt help my situation.
Upvotes: 6
Views: 5723
Reputation: 11
Setting the focus to the next control in the Enter
handler, makes the ComboBox entirely resistant to clicks and is exactly what I needed.
The comboBox1.DropDownHeight = 1;
in the accepted answer shows a weird one-pixel dropdown that looks kinda broken to my UI-sensitive eyes.
The only disadvantage I've found is that one can't Shift-Tab across the field but in my case that's not a problem.
Upvotes: 1
Reputation: 941277
Nah, not good enough. Make it disabled and look exactly like the original so the user is completely fooled. Add a new class and paste this code.
using System;
using System.Drawing;
using System.Windows.Forms;
class FakeComboBox : ComboBox {
private PictureBox fake;
public new bool Enabled {
get { return base.Enabled; }
set { if (!this.DesignMode) displayFake(value);
base.Enabled = value;
}
}
private void displayFake(bool enabled) {
if (!enabled) {
fake = new PictureBox();
fake.Location = this.Location;
fake.Size = this.Size;
var bmp = new Bitmap(fake.Size.Width, fake.Size.Height);
this.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
fake.Image = bmp;
this.Parent.Controls.Add(fake);
fake.BringToFront();
fake.Click += delegate { Console.Beep(); };
}
else {
this.Parent.Controls.Remove(fake);
fake.Dispose();
fake = null;
}
}
}
The very slight 'glow' you get on Win7 when you re-enable it is very interesting.
Upvotes: 0
Reputation: 3862
In the GotFocus hander (whatever it is called), set the focus to something else.
Upvotes: 0
Reputation: 11945
Then save his handlers as variables and simply -= them after.
Example:
var keyDown = (s, e) => e.Handled = true;
var keyPress = (s, e) => e.Handled = true;
var keyUp = (s, e) => e.Handled = true;
Then replace in his with:
comboBox1.KeyDown += keyDown;
comboBox1.KeyPress += keyPress;
comboBox1.KeyUp += keyUp;
Then when you want to remove:
comboBox1.KeyDown -= keyDown;
comboBox1.KeyPress -= keyPress;
comboBox1.KeyUp -= keyUp;
Upvotes: 0
Reputation: 11263
Setting these on your comobobox
will do the trick you are looking for, Combo is enabled but nobody can change or type anything so Appearance = Enabled, Behaviour = Disabled :)
comboBox1.DropDownHeight = 1;
comboBox1.KeyDown += (s, e) => e.Handled = true;
comboBox1.KeyPress += (s, e) => e.Handled = true;
comboBox1.KeyUp += (s, e) => e.Handled = true;
If for some reason you cannot use lambdas then following handlers can be associated. Right Click -> Paste has to be handled additionally if you have DropDownStyle = DropDown.
//void comboBox1_KeyUp(object sender, KeyEventArgs e)
//{
// e.Handled = true;
//}
//void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
//{
// e.Handled = true;
//}
//void comboBox1_KeyDown(object sender, KeyEventArgs e)
//{
// e.Handled = true;
//}
Upvotes: 6