title: How to focus a TextBox in a custom Dialog box
body: <p>I have a WPF C# desktop app and pop up a custom Dialog Window. The Dialog Window has a TextBox that I would like to be focused on so as soon as it pops up, I can type something to it without moving and pointing my cursor.</p>
  
  <p>The DialogBox is written as a class in code behind (not XAML) that goes like this:</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
  
          CustomDialog dlg = new CustomDialog();
          dlg.ShowBox();  // after the dialog box pops up, focus on the textbox.
      }
  }
  
  public partial class CustomDialog : Window
  {
      ....
      TextBox tb = new TextBox();
      ....
      public void ShowBox()
      {
         ....
         /* I want to focus on the tb as soon as CustomDialog.ShowBox() is called */
         ....
      }
  }
  </code></pre>
  
  <p>I have tried all the following, but neither of them work:</p>
  
  <pre><code>1. tb.Focus();
  2. Keyboard.Focus(tb);
  3. FocusManager.SetIsFocusScope(tb, true);
  4. Dispatcher.BeginInvoke((ThreadStart)delegate
  {
     tb.Focus();
  });
  </code></pre>
  
  <p><strong>[ANSWER]</strong></p>
  
  <p>Have to focus before showing the dialog:</p>
  
  <pre><code>tb.Focus();
  window.ShowDialog();
  </code></pre>