title: How to format textbox to display SSN as the user types
body: <p>I have a textbox which I would like to format in real time: <code>###-##-####</code> as the user types.</p>
  
  <p>I have the following code:</p>
  
  <pre><code>private bool bFlag;
  
  private void tbSSN_TextChanged(object sender, EventArgs e)
  {
      string str = tbSSN.Text;
      if (!bFlag) 
      {
          if (str.Length == 3 || str.Length == 6) 
          {
              tbSSN.Text += "-";
          bFlag = true;
          tbSSN.SelectionStart = tbSSN.Text.Length;
          } 
          else if (str.Length &gt; 11) 
          {
              tbSSN.Text = tbSSN.Text.Remove(tbSSN.Text.Length - 1);
          tbSSN.SelectionStart = tbSSN.Text.Length;
          }
      } 
      else 
      {
          bFlag = false;
      }
  }
  </code></pre>
  
  <p>The only issue is, when I hit backspace and try to enter the numbers again, it is allowing me to enter this format: <code>#####--####</code> or <code>##-#####-##</code></p>
  
  <p>I know I have to add a <code>KeyPress</code> event to ensure the above issue is resolved, but I am not sure how I would add it.</p>
  
  <p>How would I code the <code>KeyPress</code> event?</p>
  
  <p>It is a WinForm application.</p>