0

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.

Community
  • 1
  • 1
Dmitri S
  • 23
  • 1
  • 5
  • Maybe you should check to see if form is null. – LarsTech Aug 14 '17 at 21:24
  • @LarsTech The form is not null- otherwise it could not print in the first place, and I don't understand why the form would become null when it loses focus. Unless I am misunderstanding your comment. – Dmitri S Aug 14 '17 at 21:28
  • Add the following check just after your as cast. It should solve your issue. if (form == null) return; – CharithJ Aug 14 '17 at 21:33
  • You would have to debug your program to see what those values are when things go bad. Can `str` be anything else but a string? Not sure I understand why you are using generics ? You could avoid the whole issue and just pass the form reference yourself `void Print(string str, Form1 form)` – LarsTech Aug 14 '17 at 21:34
  • @LarsTech It is generic because for a time I was passing both strings and other values (ints, doubles, etc.) to it. I will try what you suggested instead. – Dmitri S Aug 14 '17 at 21:37
  • _"I don't understand why it is being thrown"_ -- it's being thrown because you have a null reference. The marked duplicate provides ample advice regarding how to debug null references and determine for yourself why they occur. If you want help fixing such errors, you need to provide a question with a problem description that is more specific than _"`NullReferenceException` is being thrown"_, with a good [mcve] that reliably reproduces the problem, and with a detailed explanation of what you've done so far to debug the problem and what _specifically_ you are having trouble figuring out. – Peter Duniho Aug 14 '17 at 22:53
  • @PeterDuniho Thank you for the explanation, I didn't realize the question wasn't detailed enough. I will try to do better in the future. – Dmitri S Aug 15 '17 at 13:49

1 Answers1

-1

ActiveForm may be null when the application doesn't have the focus.

Form.ActiveForm Property

A Form that represents the currently active form, or null if there is no active form.

Just add the null check following the cast should skip your issue. However, handling the null reference is not the resolution for your issue. You need to find a better way to pass the PDFGenerator.Form1 instance to your Print method.

var form = Form.ActiveForm as PDFGenerator.Form1;

if (form == null)
    return;
CharithJ
  • 46,289
  • 20
  • 116
  • 131
  • 1
    It is not appropriate to reopen a clear duplicate, just so you can post an answer. This is especially true when the question does not in fact have enough information for you to post a real answer. The above is pure speculation. The OP has not provided a good [mcve] that reliably reproduces the problem. Note that even if they had, and even if your answer addresses the issue, this is _exactly_ the advice found in the canonical duplicate and thus would _still_ be inappropriate and not at all a useful contribution to the Stack Overflow site. – Peter Duniho Aug 14 '17 at 22:50
  • _"The main point here is that the ActiveForm is null when it loses the focus"_ -- no, it's not. The OP claims that the exception occurs on the call to `ScrollToCaret()`. If `form` were null as you have inferred, the code never would have gotten that far, because that variable is dereferenced twice before that. In any case, the edit made to the question doesn't improve it one bit; they are still essentially asking why the exception is being thrown. They've done nothing to suggest it's anything other than an actual null reference, and dealing with those is directly addressed by the duplicate. – Peter Duniho Aug 14 '17 at 23:27
  • 1
    Thank you, even though my question was poorly framed, you answered exactly what I was asking. I didn't know about that particular property of form.Activeform. – Dmitri S Aug 15 '17 at 14:02
  • @DmitriS: I don't think your question is poorly framed. You have provided enough details and your code. And it's not about handling NullReference exceptions. It's all about the tricky ActiveForm property. Anyway I am glad that this answered your question. – CharithJ Aug 15 '17 at 14:09