1
votes

It happens while text is appending to richTextbox1 and i'm closing the program by clicking the red x on the form top right corner.

So i guess i need to handle this in the form closing event.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{

}

This is where i'm updating the richTextBox(rtbPaths)

RichTextBoxExtensions.AppendText(rtbPaths, "Downloading: ", Color.Red);
RichTextBoxExtensions.AppendText(rtbPaths, downloader.CurrentFile.Path, Color.Green);
rtbPaths.AppendText(Environment.NewLine);

This is the RichTextBoxExtensions class

public class RichTextBoxExtensions
{
    public static void AppendText(RichTextBox box, string text, Color color)
    {
        box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = box.ForeColor;
    }

    public static void UpdateText(RichTextBox box, string find, string replace, Color? color)
    {
        box.SelectionStart = box.Find(find, RichTextBoxFinds.Reverse);
        box.SelectionLength = find.Length;
        box.SelectionColor = color ?? box.SelectionColor;
        box.SelectedText = replace;
    }
}

TextChanged event

private void rtbPaths_TextChanged(object sender, EventArgs e)
{
    // set the current caret position to the end
    rtbPaths.SelectionStart = rtbPaths.Text.Length;
    // scroll it automatically
    rtbPaths.ScrollToCaret();
}

The exception message

Message=Cannot access a disposed object. Object name: 'RichTextBox'. ObjectName=RichTextBox Source=System.Windows.Forms StackTrace: at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.TextBoxBase.CreateHandle() at System.Windows.Forms.Control.get_Handle() at System.Windows.Forms.RichTextBox.get_TextLength() at DownloaderPro.Form1.RichTextBoxExtensions.AppendText(RichTextBox box, String text, Color color) in Form1.cs:line 249 at DownloaderPro.Form1.downloader_FileDownloadStarted(Object sender, EventArgs e) in Form1.cs:line 186

1
Ideally, you shouldn't have to deal with this - I mean, your code is not constructed properly somewhere. Second, you didn't show relevant code. The code you show doesn't do anything significant to text box. Third, if you closing app anyway, you can disregard any errors, which you can handle on application.threadexception event, which should be wired at app entry to handle unexpected errors.T.S.
It is most typically a threading bug, downloading large files is something you'd do with a thread. Ensuring that the download is stopped or terminated before you let the user close the window is required. Using somebody else's library to do this doesn't much help you to get this code right. Or for us to help you.Hans Passant

1 Answers

0
votes

Hi you can keep following code into closing event , it will prevent a disposing

e.Cancel = true;

Let me know if it did not work