I have a very simple custom control based on the combobox control, that just adds the ability to provide a prompt for the user and adjust the color of the prompt text. It works well, except that if I have several controls on a form, when I enter one of my custom cb controls and then try to tab on to the next control, I always have to hit tab twice before it moves to the next control. I have no idea why it is 'swallowing' the first tab key press, then works fine with the second one.
I have been researching this on StackOverflow and elsewhere for awhile now, but can't find anything addressing this issue - only advice on how to capture the tab key press by overriding the 'OnPreviewKeyDown' event, but I don't really need to do anything different with the tab key than it's already doing, I just need it to work on the first key press.
Here is the custom control code:
public partial class PromptComboBox : ComboBox
{
string prompt;
Color promptColor;
Color savedColor;
[Description("Prompt displayed to user"), Category("Appearance"), DisplayName("Prompt Text")]
public string Prompt
{
get { return prompt; }
set
{
prompt = value;
Text = prompt;
}
}
[Description("Color for Prompt Text"), Category("Appearance"), DisplayName("Prompt Color")]
public Color PromptColor
{
get { return promptColor; }
set
{
promptColor = value;
ForeColor = promptColor;
}
}
public PromptComboBox()
{
savedColor = ForeColor;
ForeColor = promptColor;
InitializeComponent();
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (SelectedIndex == 0)
{
ForeColor = promptColor;
Text = prompt;
}
else
{
ForeColor = savedColor;
}
base.OnSelectedIndexChanged(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if(char.IsLetterOrDigit(e.KeyChar) || char.IsPunctuation(e.KeyChar))
{
if (Text == prompt) Text = "";
}
base.OnKeyPress(e);
}
protected override void onke
protected override void OnKeyUp(KeyEventArgs e)
{
if (Text.Length == 0 || (Text == prompt && (e.KeyCode == Keys.Back)))
{
ForeColor = promptColor;
Text = prompt;
}
else
{
ForeColor = savedColor;
}
base.OnKeyUp(e);
}
protected override void OnEnter(EventArgs e)
{
//base.OnEnter(e);
if (Text == prompt) { Select(0, 0); }
}
protected override void OnLeave(EventArgs e)
{
if (Text.Length == 0 || Text == prompt)
{
ForeColor = promptColor;
Text = prompt;
Select(0, 0);
}
base.OnLeave(e);
}
protected override void OnClick(EventArgs e)
{
if (Text == prompt) { Select(0, 0); }
base.OnClick(e);
}
}
Any help or advice would be much appreciated!