Why not save yourself a lot of trouble and only allow the user to enter valid characters in the TextBox ? Like this:
private string legalHex = "0123456789abcdefABCDEF";
private Keys legalKeys = Keys.Space | Keys.Back | Keys.Delete;
private void HexTextBox_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = ! (legalHex.Contains((char) e.KeyValue) || legalKeys.HasFlag(e.KeyCode));
}
Note that this allows space characters to be entered, so you'd need to clean-up the string before processing it by removing all space characters:
private void btnProcessHexString_Click(object sender, EventArgs e)
{
string currentHexString = HexTextBox.Text.Replace(" ", String.Empty);
if (currentHexString.Length%2 != 0)
{
MessageBox.Show("you have not entered an even number of characters);
return;
}
// process legal hex string
}