4

Is there a way to store all of the information about the text in a richtextbox (colors, sizes, fonts, etc) and reconstruct it in another richtextbox, which is not in the same form or project?

For example, I have a richtextbox which its text contains multiple fonts and colors, and some lines are centered, and I want to reconstruct it in another richtextbox.

I added that the new richtextbox is not in the same project, so i need to restore the information somewhere (for example, even in a string or a file).

Nicolás Alarcón Rapela
  • 2,714
  • 1
  • 18
  • 29
Dani
  • 719
  • 1
  • 7
  • 14

2 Answers2

3

To copy the text and formatting from one richTextBox to another, simply use:

richtextBox2.Rtf = richtextBox1.Rtf;

The Rtf property is simply a string, so you can do with it whatever you can do with strings.

Anas Alweish
  • 2,818
  • 4
  • 30
  • 44
Heinz Kessler
  • 1,610
  • 11
  • 24
  • 1
    How are you going to do that, if they are from two different projects? – Bogdan Doicin May 25 '19 at 09:51
  • @BogdanDoicin I will write it into a file or send it through a socket. – Dani May 25 '19 at 10:14
  • @HeinzKessler Is there an event for the rtf changing? – Dani May 25 '19 at 10:16
  • No such event beyond the TextChanged. Many or most formatting is done by changing the selection first, so Selection'changed may elp. Who is doing the changes? Not your code?? – TaW May 25 '19 at 10:29
  • "Different project" means nothing. If the two projects end up being part of the same application, then you can use a totally different approach then when the two controls live on different continents. However, since rtf is nothing than strings, you can send these strings like any other string. Therefore the question here is answered, and for the rest of his problem, he will find answers elsewhere in SO. – Heinz Kessler May 25 '19 at 11:58
0

You can do that with the following steps

assume we have two projects

the first is WinFormApp1 and the second is WinFormApp2

  1. Save the RTF of the RichTextBox1 in WinFormApp1 in a text file

    In WinFormApp1

        const string path = @"D:\RichTextBox\Example.txt";
    
        var rtbInfo = richTextBox1.Rtf;
    
        if (!File.Exists(path))
        {
            File.Create(path);
            TextWriter textWriter = new StreamWriter(path);
            textWriter.WriteLine(rtbInfo);
            textWriter.Close();
        }
        else if (File.Exists(path))
        {
             File.WriteAllText(path, rtbInfo);
        }
    
  2. Read the data from the text file and assigned to RTF of the RichTextBox1 in WinFormApp2

    In WinFormApp2

    private void Form1_Load(object sender, EventArgs e)
    {
        const string path = @"D:\RichTextBox\Example.txt";
    
        if (File.Exists(path))
        {
            richTextBox1.Rtf = System.IO.File.ReadAllText(path);
        }
    }
    
Anas Alweish
  • 2,818
  • 4
  • 30
  • 44