Inability to properly load Rtf to a RichTextBox - c#

I have a custom RichTextBox that derives from the RichTextBox base class. Its purpose is to display formatted text. However, any Rtf loaded is displayed as simple text without any formatting: font, font-size, font-style etc.
I have tried the following code to load the Rtf: (Note: rtbEx is the extended richtextbox control; RTF is a string containing the Rtf)
Using a file stream:
FileStream tempFile = File.Open(#"C:\RTF.rtf", FileMode.Open);
tempFile.Position = 0;
rtbEx.LoadFile(tempFile, RichTextBoxStreamType.RichText);
tempFile.Close();
Loading from the specified path:
rtbEx.LoadFile(#"C:\Users\Wilbur Omae\Desktop\RTF.rtf", RichTextBoxStreamType.RichText);
Directly setting the Rtf:
rtbEx.Rtf = RTF;
On checking the Rtf of the rtbEx, it seems to be perfect Rtf, yet it is displayed as plain text.
What could be the issue?
Update 1:
The custom RichTextBox is a control within a custom Form which it to be displayed as a TabPage.

you can use Clipboard in this case :
Clipboard.SetText(RichTextBox1.Rtf, TextDataFormat.Rtf);
and paste it
RichTextBox1.Text= Clipboard.GetText()
It works for me .. try it

As a workaround, I ensured the Rtf was set only when the form had been shown by trapping the Form.Shown event as shown below:
public class SermonReader : Form
{
public RichTextBoxEx rtbEx= new RichTextBoxEx();
private string RTF = "";
public SermonReader(string rtf)
{
RTF = rtf;
Shown += new EventHandler(ehFormShown);
FormBorderStyle = FormBorderStyle.None;
TopLevel = false;
Controls.Add(rtbEx);
rtbEx.Dock = DockStyle.Fill;
}
private void ehFormShown(object sender, EventArgs e)
{
rtbEx.Rtf = RTF;
}
}
I don't know why the issue is this complicated but I hope this helps.
Any other solution? Feel free to comment or answer.

I had the same problem with a richtextbox within a winformscontrol
within a dialog (MFC), the rtb should be filled with rtf, but
after setting RichTextBox.Rtf, loading from file or Clipboard it all was unformatted.
I could solved it by using Postmessage in OnInitDialog with UpdataData(FALSE) (Sets RichTextBox.Rtf again)
in the handler. seems as if creation yet was not complete ..

Related

C# display html code control needed

I'm looking for a control that be able to show HTML code like shown is the following image:
I just need to show the HTML code loaded and display it without any edition.
I do not find it anywhere.
Any help?
Based on the info you've provided;
Create a new Form
Add a Close button to it
Add a TextBox and set it to ReadOnly
Set the .Text property in the TextBox to the HTML to show.
If you do want syntax highlighting, check for open source projects on GitHub or articles on codeproject.com
Assuming you have a WinForm and a text box called txHTML to display the text, and a textbox called txUrl to provide the url you want the html from. Put this on a button click event to fill your txHTML with what you desired.
protected void Get_Click(object sender, EventArgs e){
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(txUrl.Text);
// get the response
HttpWebResponse WebResp = (HttpWebResponse)wr.GetResponse();
string res = "";
using (StreamReader sr = new StreamReader(WebResp.GetResponseStream()))
{
res = sr.ReadToEnd();
sr.Close();
}
WebResp.Close();
txHTML.Text = res;
}

RichTextBox not showing the text

I am trying to create a Bitmap from a RichTextBox and set it as the background image for a panel, but unfortunately the text is not shown.
Bitmap l_bitmap = new Bitmap(m_control.Width, m_control.Height);
m_control.DrawToBitmap(l_bitmap, new Rectangle(0, 0, l_bitmap.Width, l_bitmap.Height));
m_panel.BackgroundImage = l_bitmap;
m_panel.Refresh();
m_control is my RichTextBox. When I debug, I can see that the control contains the text I wrote, but the bitmap just shows an empty RichTextBox.
I use the same code for other types of controls (Button, CheckBox, TextBox...). The text is shown with no problems.
Well you are trying to create a bitmap from the control. The text you put in there isn't the control, so it won't bother to chow it as bitmap. Try to create a picture from screen (like a screenshot).
Example:
Graphics gr = Graphics.FromImage(l_bitmap);
gr.CopyFromScreen(m_control.PointToScreen(Point.Empty), point.Empty, m_control.Size);
This will make a bitmap from your given points. This will additional show you the text.
EDIT
Maybe you can use this instead. In addition to your idea, I simply put a label onto my panel. (L for Label and P for Panel)
As you can see, the label is empty because I cleared the Text property. Now, when you click one of the buttons below the panel, it will update the label.Text propertie and there will be the text you gave the control.
Here is some example:
As you can see, the label shows the Name of the control. Completly custom as you can see on my source code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public RichTextBox tmpRtf = new RichTextBox();
//Poor button name incoming...
private void button1_Click(object sender, EventArgs e)
{
if (tmpRtf == null)
tmpRtf = new RichTextBox();
//You can add any text here and it will be shown on the label.
this.tmpRtf.Text = "Richtextbox";
this.UpdatePanel(this.tmpRtf);
}
//Custom method to update the panel for any control. Can pobably be done way better than this, but hey.
private void UpdatePanel(object pControl)
{
//Checks if control is a rtf
if(pControl is RichTextBox)
{
//This is your code! Ay.
Bitmap l_bitmap = new Bitmap(this.panel1.Width / 2, this.panel1.Height / 2);
(pControl as RichTextBox).DrawToBitmap(l_bitmap, new Rectangle(0, 0, l_bitmap.Width, l_bitmap.Height));
this.tmpRtf.BackColor = Color.LightGray;
this.panel1.BackgroundImage = l_bitmap;
this.panel1.BackgroundImageLayout = ImageLayout.Center;
this.labelControlName.Text = this.tmpRtf.Text;
this.panel1.Refresh();
}
}
}
Its not possible to show text on a control thats not visualized. But you can build a workaround! Or, instead of taking a picture you can simply create the control on top of it, that will also show the Text and maybe the user can test it (e.g. click on buttons, look at the control behaviour).
Hopefully this is something to get you inspired that there are always more ways to accomplish.

c# wpf export RichTextBox formatting to xml document

so in WPF i've created a RichTextBox and implemented the functionality to be able to format selected text (bold, undelined, font, etc...), but now i would like to export all of the formatting to a XML file, so when i would load it the loaded file would give me the same text with the same formatting.
I think that the best way to do this would be, if i could find each place where there is formatting in the RTB and then save it as a text range, but i dont know if RTB has a method for finding if a part of text is formatted.
Here is what i've got:
xaml:
<Button Name = "export" Click = "export_Click"/>
<RichTextBox x:Name="RTB"/>
and the c#:
private void export_Click(object sender, RoutedEventArgs e){
TextRange range = new TextRange();
//here is where i want to access the formatted areas
//something like: range = RTB.document.getBoldArea();
//and then i could export what i got in the text range to a xml file
}
thanks in advance to anyone willing to help!
You can actually access XAML content directly, which is itself obviously XML. You could either save this directly or manipulate/translate it into your own schema.
To get the XAML for a RichTextBox :
static string GetXaml(RichTextBox rt)
{
TextRange range = new TextRange(rt.Document.ContentStart, rt.Document.ContentEnd);
MemoryStream stream = new MemoryStream();
range.Save(stream, DataFormats.Xaml);
string xamlText = Encoding.UTF8.GetString(stream.ToArray());
return xamlText;
}
To set the XAML content for a RichTextBox :
static void SetXaml(RichTextBox rt, string xamlString)
{
StringReader stringReader = new StringReader(xamlString);
XmlReader xmlReader = XmlReader.Create(stringReader);
Section sec = XamlReader.Load(xmlReader) as Section;
FlowDocument doc = new FlowDocument();
while (sec.Blocks.Count > 0)
doc.Blocks.Add(sec.Blocks.FirstBlock);
rt.Document = doc;
}

C# - RichTextBoxPrintCtrl and tabcontrol

Hello (and sorry for my English), I have a problem with Printing RTF using RichTextBoxPrintCtrl and TabControl.
1) The tabcontrol got no tabs on Design, when the Form Load, it will get a tab with the method AddTab(Title). (Don't mind about other variables).
private void AddTab(string Name = "Nuova Nota*")
{
RichTextBox Body = new RichTextBox();
Body.Name = "Body";
Body.Dock = DockStyle.Fill;
Body.ContextMenuStrip = contextMenuStrip1;
TabPage NewPage = new TabPage();
string DocumentText = Nome;
if (Nome == "Nuova Nota*")
{
TabCount += 1;
DocumentText = Nome + TabCount;
}
NewPage.Name = DocumentText;
NewPage.Text = DocumentText;
tabControl1.Visible = true;
NewPage.Controls.Add(Body);
tabControl1.TabPages.Add(NewPage);
tabControl1.SelectedTab = NewPage;
Nomi_Files.Add(NewPage.Text);
Path_Files.Add("");
}
2) Once the tab is created, you can start to write, change colors, fonts, etc...
To get access on the document that you are making, i use a GetCurrentDocument that return the "Body" of the selected tab:
private RichTextBox GetCurrentDocument
{
get { return (RichTextBox)tabControl1.SelectedTab.Controls["Body"];}
}
Now, all the functions (save, open, fonts, colors...) Works Fine, i wanted to print my document and keep the style, so i Googled and i found this: How to print the content of a RichTextBox control by using Visual C#
I made the RichTextBoxPrintCtrl.dll, added the resource on my project, added the item inside the toolbox, but i can't change the RichTextBox that i create from Code, with RichTextBoxPrintCtrl.
The error that i get is:
Error 1 'RichTextBoxPrintCtrl' is a 'namespace' but is used like a
'type'
How i can use that RichTextBoxPrintCtrl without drag and drop it inside the design form?
Ok, i figured out how to solve it:
instead of declaring like:
RichTextBoxPrintCtrl NameControl = new RichTextBoxPrintCtrl();
we need to declare the namespace so:
RichTextBoxPrintCtrl.RichTextBoxPrintCtrl NameControl = new RichTextBoxPrintCtrl.RichTextBoxPrintCtrl();
Everything works fine :) thanks;

VSTO Word Add-In : Content Control Nesting

I'm building an MS-Word Add-In for the company where I'm doing my internship.
I already created a new ribbon with lots of SplitButtons and Buttons.
Now what i want to do is when you click one of the buttons a content control will ba added to the word doc.
This works fine for Plain Content Controls. These content controls have tags like "sport/basketball/player/name" which is binded to an element in an XML file.
private void addSimpleContentControl(String tag, String placeholder)
{
try
{
contentControlPlain = Globals.ThisAddIn.Application.ActiveDocument.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText);
contentControlPlain.Tag = tag;
contentControlPlain.SetPlaceholderText(null, null, placeholder);
}
catch (COMException) { }
}
Now let's talk about my problem.
Some of my elements could be present for more then one time. So what i want to create is a Rich Content control which holds more than one Plain content control.
So i have a SplitButton "player" with buttons like "name","jersey number","position",.....
When one of the underlying buttons is clicked i first check if a rich text control with a specific name already exist.
If not than i make one and add one single Plain content control to it.
Rich content control-> plain text control -> end of Rich content control
So far so good, this all goes fine but from the moment i want to add another plain content control to the rich content control this pops up :
"Plain text controls cannot be inserted around other controls or XML elements"
here is my code to add a plain content control to a rich content control.
private void addContentControlToRich(String tag, String placeholder,String title)
{
Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
foreach (Microsoft.Office.Interop.Word.ContentControl cc in doc.ContentControls)
{
if (cc.Title == title && cc.Type == Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlRichText)
{
try
{
Microsoft.Office.Interop.Word.Range rng = cc.Range;
object oRng = rng;
contentControlPlain = doc.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);
contentControlPlain.Tag = tag;
contentControlPlain.SetPlaceholderText(null, null, placeholder);
contentControlPlain.LockContentControl = true;
break;
}
catch (COMException) { }
}
}
}
instead of
contentControlPlain = doc.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);
use
contentControlPlain = richTextControl.Range.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);
before using above code use code below
Application.Selection.Start = lastControlinRichTextControl.Range.End+1;
and set `oRng = Application.Selection.Range
As per the message, your code is trying to wrap a plain text control around everything in the rich text control (ie an existing plain text control). Fix your range object so that it doesn't do that eg collapse it to just a point inside the rich text control.

Categories