title: ScrollToCaret throws null reference exception when focus lost
body: <p>I am creating a C# WinForms app that creates PDFs and outputs the name of each PDF into a rich text box as it is created. I am using the ScrollToCaret functionality to automatically scroll the textbox down as each line is created. As an additional detail, the print method is in a separate class from the WinForm.</p>
  <p>The issue I am running into is that whenever the program loses focus, the ScrollToCaret function throws a NullReferenceException</p>
  <p>This is the segment of code that throws the error each time:</p>
  <pre><code>private void Print&lt;T&gt;(T str)
      {
          var form = Form.ActiveForm as PDFGenerator.Form1;
          
          try
          {
              form.richTextBox1.AppendText(str + Environment.NewLine);
          }
          catch
          {
              form.richTextBox1.AppendText(&quot;Couldn't print string&quot;);
          }
  
          form.richTextBox1.ScrollToCaret();
      }
  </code></pre>
  <p>with the additional text</p>
  <blockquote>
  <p>An unhandled exception of type 'System.NullReferenceException' occurred in PDFGenerator.exe</p>
  <p>Additional information: Object reference not set to an instance of an object.</p>
  </blockquote>
  <p>The program does not run into any issues if it does not lose focus, but if it ever loses focus while generating the PDFs it consistently throws this exception.</p>
  <p>The program takes a minute or two to run, so the ability to run it in the background is important.</p>
  <p>How do I stop ScrollToCaret from throwing a Null Reference exception when the program loses focus? Do I have to use some other function of WinForms RichTextBox?</p>
  <p><strong>EDIT:</strong> I understand what a null reference exception is; I don't understand why it is being thrown when the winform is clearly instantiated and functioning, but ceases to function so when the program loses focus. I have not found any documentation saying that a winform or its child components uninstantiate when the winform loses focus.</p>