chuches
chuches

Reputation: 13

How to pass text formatted from a Windows Form to the Word application?

I have a RichTextBox in which I write text and I give it color and format and what I want is that when I press a button that I have programmed, I open the Word application and pass the text that I have in the RichTextBox to the Word document, along with the color and format that I have given in my application.

I have the following code that opens Word and it passes the text that I had in the RichTextBox but the problem is that it does not show me the color and format that I had in the text in my application.

colorLetra = new ColorDialog();
objWord = new Word.Application();
objWord.Visible = true;
objDocumento = objWord.Documents.Add(Missing.Value);
objWord.Selection.Font.Color = objWord.Selection.Font.Color;
objWord.Selection.TypeText(richTextBox.Text);

Could you tell me why it does not show me the color and format in Word?

Upvotes: 1

Views: 346

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25673

Your question is:

Could you tell me why it does not show me the color and format in Word?

The reason is because you only enter/type the text. You don't apply any formatting. You're simply transferring the string value of the Windows Forms control to the Word document, as a string.

Your implied question is: How do I pass formatted RichTextBox content to Word...

There is no way to directly pass formatted information from a Windows Form to a Word document. You must go over the clipboard, as was suggested in a comment. The code that comments points to, however, is incorrect for formatted text. The following works for me:

    if (richTextBox.Text.Length > 0)
    {
        // Copy the formatted content to the clipboard
        Clipboard.SetText(richTextBox.Rtf, TextDataFormat.Rtf);
        objWord.Selection.Paste();
    }

Upvotes: 1

Related Questions