c# - ScrollToCaret throws null reference exception when focus lost -


this question has answer here:

i creating c# winforms app creates pdfs , outputs name of each pdf rich text box created. using scrolltocaret functionality automatically scroll textbox down each line created. additional detail, print method in separate class winform.

the issue running whenever program loses focus, scrolltocaret function throws nullreferenceexception

this segment of code throws error each time:

private void print<t>(t str)     {         var form = form.activeform pdfgenerator.form1;          try         {             form.richtextbox1.appendtext(str + environment.newline);         }         catch         {             form.richtextbox1.appendtext("couldn't print string");         }          form.richtextbox1.scrolltocaret();     } 

with additional text

an unhandled exception of type 'system.nullreferenceexception' occurred in pdfgenerator.exe

additional information: object reference not set instance of object.

the program not run issues if not lose focus, if ever loses focus while generating pdfs consistently throws exception.

the program takes minute or 2 run, ability run in background important.

how stop scrolltocaret throwing null reference exception when program loses focus? have use other function of winforms richtextbox?

edit: understand null reference exception is; don't understand why being thrown when winform instantiated , functioning, ceases function when program loses focus. have not found documentation saying winform or child components uninstantiate when winform loses focus.

activeform may null when application doesn't have focus.

form.activeform property

a form represents active form, or null if there no active form.

just add null check following cast should skip issue. however, handling null reference not resolution issue. need find better way pass pdfgenerator.form1 instance print method.

var form = form.activeform pdfgenerator.form1;  if (form == null)     return; 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -