Is it possible to style text in a richtextbox at d

2019-03-29 06:47发布

问题:

I have a System.Windows.Forms.RichTextBox that I wish to use to display some instructions to my application users.

Is it possible to set some of the text I enter at designtime to be bold?

Or do I have no option but to do it at runtime?

回答1:

You can certainly create an RTF document in RTF editor (e.g. WordPad), save the file, open it as a text/plain file and copy the RTF document into the RtfText property of your RichTextBox at design time.

But I advise against it. That way, you have a large amount of data in your code and there’s just no point in doing that. Use a resource, that’s what they’re there for, after all. You can bind individual resources to control properties at design time.



回答2:

Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the tool box onto your form. Select the RichText property and click the button with the dots. That will start Wordpad. Edit your text, type Ctrl+S and close Wordpad. Beware that the Visual Studio designer is non-functional while Wordpad is open.

Imports System.ComponentModel
Imports System.Drawing.Design
Imports System.IO
Imports System.Diagnostics

Public Class MyRtb
    Inherits RichTextBox

    <Editor(GetType(RtfEditor), GetType(UITypeEditor))> _
    Public Property RichText() As String
        Get
            Return MyBase.Rtf
        End Get
        Set(ByVal value As String)
            MyBase.Rtf = value
        End Set
    End Property

End Class

Friend Class RtfEditor
    Inherits UITypeEditor

    Public Overrides Function GetEditStyle(ByVal context As ITypeDescriptorContext) As UITypeEditorEditStyle
        Return UITypeEditorEditStyle.Modal
    End Function

    Public Overrides Function EditValue(ByVal context As ITypeDescriptorContext, ByVal provider As IServiceProvider, ByVal value As Object) As Object
        Dim fname As String = Path.Combine(Path.GetTempPath, "text.rtf")
        File.WriteAllText(fname, CStr(value))
        Process.Start("wordpad.exe", fname).WaitForExit()
        value = File.ReadAllText(fname)
        File.Delete(fname)
        Return value
    End Function
End Class


回答3:

I found this link on codeproject to be very useful:

http://www.codeproject.com/KB/miscctrl/richtextboxextended.aspx

It is a fully working rtf-editing control build around the standard .net RichtTextBox control with a good structured code. It shows how to use nearly every available feature of the control.

However, it is written in c# and not vb.net but you should definetly take a look.



回答4:

Bravo - simple and efficient! Here is also small correction, because argument is long string with spaces so next line contains required quotes:

Process.Start("wordpad.exe", """" & fname & """").WaitForExit()