[英]How can I save the content of a rich text box even when the form closes?
This is my first post here, so please don't judge me if I write something wrong ^^这是我在这里的第一篇文章,所以如果我写错了,请不要评判我^^
Anyways, I've recently run into an issue with richtextboxes in Visual Basic .NET and WinForms.无论如何,我最近在 Visual Basic .NET 和 WinForms 中遇到了丰富文本框的问题。 Let's say I have a Main form and a Log form.假设我有一个主窗体和一个日志窗体。 The log form contains a richtextbox which functions as a log.日志表单包含一个用作日志的富文本框。 From the main form I'm writing text to the log and I also format the lines, so they have different colors (blue for information, red for error).在主窗体中,我正在向日志中写入文本,并且还对行进行格式化,因此它们具有不同的 colors(蓝色表示信息,红色表示错误)。 Unfortunately, whenever I close and reopen the log form all text that has been written to it is lost.不幸的是,每当我关闭并重新打开日志表单时,所有已写入其中的文本都会丢失。 I've tried saving it to a text file, but that doesn't save the colors of the text.我试过将它保存到文本文件中,但这并没有保存文本的 colors。
Is there any way I can save the text and the colors of the lines even when the form closes?即使表单关闭,有什么方法可以保存文本和行的 colors 吗?
Here's what the excellent suggestion from Shrotter might look like:以下是 Shrotter 的优秀建议可能是这样的:
Public Class Form1
Private RtfPath As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim folder As String = System.IO.Path.GetDirectoryName(Application.ExecutablePath)
RtfPath = System.IO.Path.Combine(folder, "RtbData.rtf")
If System.IO.File.Exists(RtfPath) Then
RichTextBox1.LoadFile(RtfPath)
End If
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
RichTextBox1.SaveFile(RtfPath)
End Sub
End Class
Of course, you should always wrap the loading/saving of the file in a Try/Catch block in case anything goes wrong.当然,您应该始终将文件的加载/保存包装在 Try/Catch 块中,以防出现任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.