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.
The issue I am running into is that whenever the program loses focus, the ScrollToCaret function throws a NullReferenceException
This is the segment of code that throws the error each time:
private void Print<T>(T str)
{
var form = Form.ActiveForm as PDFGenerator.Form1;
try
{
form.richTextBox1.AppendText(str + Environment.NewLine);
}
catch
{
form.richTextBox1.AppendText("Couldn't print string");
}
form.richTextBox1.ScrollToCaret();
}
with the additional text
An unhandled exception of type 'System.NullReferenceException' occurred in PDFGenerator.exe
Additional information: Object reference not set to an instance of an object.
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.
The program takes a minute or two to run, so the ability to run it in the background is important.
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?
EDIT: 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.