首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >关闭程序时,如何处理无法访问已释放的对象异常?

关闭程序时,如何处理无法访问已释放的对象异常?
EN

Stack Overflow用户
提问于 2017-01-29 01:35:53
回答 1查看 985关注 0票数 1

当文本附加到richTextbox1时会发生这种情况,而我将通过单击窗体右上角上的红色x来关闭程序。

所以我想我需要在表单闭幕式上处理这件事。

代码语言:javascript
运行
复制
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{

}

这是我更新richTextBox(rtbPaths)的地方

代码语言:javascript
运行
复制
RichTextBoxExtensions.AppendText(rtbPaths, "Downloading: ", Color.Red);
RichTextBoxExtensions.AppendText(rtbPaths, downloader.CurrentFile.Path, Color.Green);
rtbPaths.AppendText(Environment.NewLine);

这是RichTextBoxExtensions类

代码语言:javascript
运行
复制
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事件

代码语言:javascript
运行
复制
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();
}

异常消息

Message=Cannot访问已释放的对象。对象名称:“RichTextBox”。System.Windows.Forms.TextBoxBase.CreateHandle() at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.Control.get_Handle() at System.Windows.Forms.RichTextBox.get_TextLength() at DownloaderPro.Form1.RichTextBoxExtensions.AppendText(RichTextBox box,String text,颜色)在Form1.cs中: DownloaderPro.Form1.downloader_FileDownloadStarted(Object发件人处的第249行,Form1.cs中的EventArgs e):第186行

EN

回答 1

Stack Overflow用户

发布于 2017-01-29 06:09:39

嗨,您可以继续按照下面的代码进入关闭事件,这将防止处理

代码语言:javascript
运行
复制
e.Cancel = true;

如果它不起作用,请告诉我

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41916781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档