title: C# textBox Hex only with 0x/h/$ prefix using TextChanged property
body: <p>I am testing the following code in TextChanged property to allow only HEX values in the textBox and it works just fine, it also deletes pasted string which doesn't match the HEX pattern and converts the lower to upper case, this is just what I needed:</p>
  
  <pre><code>Regex nonhex = new Regex("[^0-9,a-f,A-F]");
  int caret = textBox1.SelectionStart - textBox1.Text.Length;
  textBox1.Text = nonhex.Replace(textBox1.Text, "").ToUpper();
  textBox1.SelectionStart = caret + textBox1.Text.Length;
  </code></pre>
  
  <p>If I try to add a prefix, the above code simply deletes it. What is the best way to modify the code in order to allow adding a permanent prefix (sth like 0x, h, $) such that I only use regular Expressions and TextChnaged property, is it possible anyway? I also need to be able to specify the max length of the HEX value, for example 4 digits for a PID and VID HID device, because I might use it in some different project which will need more or less hex digits..</p>
  
  <p>I looked in the forum for a similar solution, but most people use more than one event and barely achieve what these four lines can do. Using RegEx is not a border-line crime BTW..</p>
  
  <p>thanks</p>