RichTextBox --> Change Font for specific line - c#

I want to change the font in a specific line. Here's my code...
string[] textBoxLines = richTextBox1.Lines;
foreach (string line in textBoxLines)
{
if(line.StartsWith("-->"))
{
//here is my problem, how to can change the font in the spectific line...
}
}

string[] textBoxLines = richTextBox1.Lines;
for (int i = 0; i < textBoxLines.Length; i++)
{
string line = textBoxLines[i];
if (line.StartsWith("-->"))
{
richTextBox1.SelectionStart = richTextBox1.GetFirstCharIndexFromLine(i);
richTextBox1.SelectionLength = line.Length;
richTextBox1.SelectionFont = yourFont;
}
}
richTextBox1.SelectionLength = 0;//Unselect the selection

Related

C# Text in Powerpoint shape not being detected

I'm trying to extract all the text in each slide of a powerpoint file. For some reason I'm only getting some text and not all of them. I'm looping through all shapes in the slide and checking for both textframes and tables. But some slides with text will print out nothing.
Here's a sceenshot of the slide that only printed the title and no other text.
Code
foreach (PowerPoint.Slide _slide in pptPresentation.Slides) {
foreach(PowerPoint.Shape _shape in _slide.Shapes) {
//check for textframes
if (_shape.HasTextFrame == MsoTriState.msoTrue) {
var textFrame = _shape.TextFrame;
if (textFrame.HasText == MsoTriState.msoTrue) {
var textRange = textFrame.TextRange;
PrintAllParagraphs(textRange);
}
}
//check for tables
if(_shape.HasTable == MsoTriState.msoTrue) {
var slideTable = _shape.Table;
int rowCount = slideTable.Rows.Count;
int colCount = slideTable.Columns.Count;
for(int y = 1; y <= rowCount; y++) {
for(int x = 1; x <= colCount; x++) {
var tRange = slideTable.Cell(y, x).Shape.TextFrame.TextRange;
PrintAllParagraphs(tRange);
}
}
}
} //loop shapes
} //loop slides
print function
public void PrintAllParagraphs(PowerPoint.TextRange textRange) {
for (int i = 1; i <= textRange.Paragraphs().Count; i++) {
PowerPoint.BulletFormat bulletFormat = textRange.Paragraphs(i).ParagraphFormat.Bullet;
Console.WriteLine( (bulletFormat.Type == PowerPoint.PpBulletType.ppBulletNone) ? textRange.Paragraphs(i).Text.ToString() : "* " + textRange.Paragraphs(i).Text.ToString());
}
}
Are there other things i should be checking within the shape of a slide? Any help would be appreciated. Thanks.
Okay, turns out that this is a SmartArt that's the reason why checking Shapes/Tables did not detect it.
All i had to do was to loop the nodes within the Smart Art and grab the text from TextRange. I noticed the text is seperated by "\r" so by splitting it i was able to get the correct output from it.
//check for SmartArt
if(_shape.HasSmartArt == MsoTriState.msoTrue) {
foreach( SmartArtNode node in _shape.SmartArt.AllNodes) {
var txtRange = node.TextFrame2.TextRange;
var txt = txtRange.Paragraphs.Text.Split(new string[] { "\r" }, StringSplitOptions.None);
foreach(string line in txt)
Console.WriteLine(line);
}
}

Limit line length in multiline textbox

I need to limit the number of characters on a single line that a user can enter into a multiline textbox. I have a function that can do that for data typed in, but not for data cut and pasted in.
I've tried reading the textbox into an array, using substring, and copying back to the text string, but this code (posted) throws an exception.
private void LongLine_TextChanged(object sender, TextChangedEventArgs e)
{
int lineCount =
((System.Windows.Controls.TextBox)sender).LineCount;
//string newText = "";
for (int i = 0; i < lineCount; i++)
{
if
(((System.Windows.Controls.TextBox)sender).GetLineLength(i) > 20)
{
string textString = ((System.Windows.Controls.TextBox)sender).Text;
string[] textArray = Regex.Split(textString, "\r\n");
textString = "";
for (int k =0; k < textArray.Length; k++)
{
String textSubstring = textArray[k].Substring(0, 20);
textString += textSubstring;
}
((System.Windows.Controls.TextBox)sender).Text = textString;
}
}
e.Handled = true;
}
This does what you seem to be asking for:
It truncates the end of any line that is longer than 20 as you type and when you paste or otherwise change the text.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
const int MAX_LINE_LENGTH = 20;
var textbox = sender as TextBox;
var exceedsLength = false;
// First test if we need to modify the text
for (int i = 0; i < textbox.LineCount; i++)
{
if (textbox.GetLineLength(i) > MAX_LINE_LENGTH)
{
exceedsLength = true;
break;
}
}
if (exceedsLength)
{
// Split the text into lines
string[] oldTextArray = textbox.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var newTextLines = new List<string>(textbox.LineCount);
for (int k = 0; k < oldTextArray.Length; k++)
{
// truncate each line
newTextLines.Add(string.Concat(oldTextArray[k].Take(MAX_LINE_LENGTH)));
}
// Save the cursor position
var cursorPos = textbox.SelectionStart;
// To avoid the text change calling back into this event, detach the event while setting the Text property
textbox.TextChanged -= TextBox_TextChanged;
// Set the new text
textbox.Text = string.Join(Environment.NewLine, newTextLines);
textbox.TextChanged += TextBox_TextChanged;
// Restore the cursor position
textbox.SelectionStart = cursorPos;
// if at the end of the line, the position will advance automatically to the next line, supress that
if (textbox.SelectionStart != cursorPos)
{
textbox.SelectionStart = cursorPos - 1;
}
}
e.Handled = true;
}

Adding an Items into Listview

I have completely split the string in text file that is delimited by a comma.
My problem is that I cannot show the data on my list view.
I have use this code, but when I run it and debug, there is value inside the variables. but then I finished the debugging, No Items were added in the Listview.
private void ColumnHeaders()
{
lvResult.View = View.Details;
lvResult.Columns.Add("ファイル名");
lvResult.Columns.Add("フォルダ");
lvResult.Columns.Add("比較結果");
lvResult.Columns.Add("左日付");
lvResult.Columns.Add("右日付");
lvResult.Columns.Add("拡張子");
for (int i = 0; i <= lvResult.Columns.Count; i++)
{
lvResult.Columns[i].Width = lvResult.Width / 6;
}
}
private void viewTextFile()
{
string[] lines = File.ReadAllLines(txtResultPath.Text + "A.YMD6063_new.txt");
for (int x = 0 ; x <= lines.Length; x++)
{
string[] col = lines[x].Split(new char[] { ',' });
ListViewItem lvItem = new ListViewItem();
for (int i = 0; i <= col.Length; i++)
{
lvItem.Text = col[i].ToString();
if (i == 0)
{
lvResult.Items.Add(lvItem);
}
else
{
lvResult.Items[x].SubItems[i].Text = lvItem.Text;
}
}
}
}
here is a sample code I tried. Hope this would help you.
listView1.Columns.Add("column1");
listView1.Columns.Add("column2");
listView1.Columns.Add("column3");
listView1.Columns.Add("column4");
string[] lines = new string[] { "value01,value02,value03,value04", "value11,value12,value13,value14" };
foreach (string line in lines)
{
listView1.Items.Add(new ListViewItem(line.Split(',')));
}
Set the ListView.View to Details. This can either be achieved in the Designer or programatically like this:
lvResult.View = View.Details;
Add each line of your file:
private void viewTextFile()
{
foreach(var line in File.ReadAllLines(somefilepath))
AddLineToListView(line);
}
private void AddLineToListView(string line)
{
if (string.IsNullOrEmpty(line))
return;
var lvItem = new ListViewItem(line.Split(','));
lvResult.Items.Add(lvItem);
}

Skip text in RichTextBox

I would skip the text in the field, if there is no text, but if this is to add text to the beginning and the end. I'm trying like this but it add text every line.
private void zmien(string a, string b)
{
{
if (richTextBox1.Text.Length > 0)
{
string[] lines = richTextBox1.Lines;
for (int i = 0; i < lines.Length; i++)
{
if (richTextBox1.Text.Length == 0)
{
for (int j = 0; i < lines.Length; i++)
lines[i] = Environment.NewLine;
}
else
lines[i] = a + lines[i] + b;
}
richTextBox1.Lines = lines;
//richTextBox1.SelectedText = "test" + lines;
}
}
}
You can do that much simply as you think, try follow this code
private void zmien(string a, string b)
{
if (richTextBox1.Text.Length > 0)
{
richTextBox1.Text = a+" "+richTextBox1.Text+" "+b;
}
}

using WPF can I do auto word replacement when a user is typing in richtextbox

public void overallTextReplace(RichTextBox[] rtb) {
string[] keyword = { "FCI", "CNG", "DCR", "EZR", "VASC", "CND" };
string[] newString = { "Forecourt Controller","Case Number Declined" ,"Case Number Given", "Dispenser Card reader", "Enhanced Zone Router", "Verifone Authorized Service Contractor" };
TextRange[] text = new TextRange[rtb.Length];
for (int I = 0; I < rtb.Length; I++) {
text[I] = new TextRange(rtb[I].Document.ContentStart, rtb[I].Document.ContentEnd);
}
for (int I = 0; I < text.Length; I++) {
for (int K = 0; K < keyword.Length; K++) {
TextPointer current = text[I].Start.GetInsertionPosition(LogicalDirection.Forward);
string textInRun = current.GetTextInRun(LogicalDirection.Forward);
if (!string.IsNullOrEmpty(textInRun)) {
int index = textInRun.IndexOf(keyword[K]);
if (index != -1) {
TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
TextPointer selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward);
TextRange selection = new TextRange(selectionStart, selectionEnd);
selection.Text = newString[K];
selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);
rtb[I].Selection.Select(selection.Start, selection.End);
rtb[I].Focus();
}
}
current = current.GetNextInsertionPosition(LogicalDirection.Forward);
}
}
}
okay so this code will look through all RichTextBoxs in the WPF form when passed in to the function, it will then look for the keywords listed and replace them with the newString. the problem im having is that the program only looks on one line of text from start to finish. If it detects a newline it will not look past it for example: line1: the FCI is a fuel controller. it replaces it just fine but if i have more on line 2 it will not make the replace. if it makes any difference their are 6 richTextBoxes being passed in to this function.
just found an error, but it has nothing to do with my first issue. so it seems that having 6 array indexes prevents the code from running and throws a null ref on TextRange selection = new Textrange(selectionStart, selectionEnd);
but if i use VASC as the word to be replaced their is no exception. I am not sure why.
For winforms:
Try this(Though I haven't run this code but logically it should work) :
public void overallTextReplace(RichTextBox[] rtb)
{
string[] keyword = { "FCI", "CNG", "DCR", "EZR", "VASC", "CND" };
string[] newString = { "Forecourt Controller","Case Number Declined" ,"Case Number Given", "Dispenser Card reader", "Enhanced Zone Router", "Verifone Authorized Service Contractor" };
for (int i = 0; i < rtb.Length; i++)
{
for (int j = 0; j < 6; j++)
{
rtb[i].Rtf=rtb[i].Rtf.Replace(keyword[j],newString[j]);
}
}
}
For wpf:
for (int i = 0; i < rtb.Length; i++)
{
RichTextBox rtb_wording= rtb[i];
var textRange = new TextRange(rtb_wording.Document.ContentStart, rtb_wording.Document.ContentEnd);
string rtf;
using (var memoryStream = new MemoryStream())
{
textRange.Save(memoryStream, DataFormats.Rtf);
rtf = ASCIIEncoding.Default.GetString(memoryStream.ToArray());
}
for (int j = 0; j < 6; j++)
{
rtf =rtf.Replace(keyword[j],newString[j]);
}
MemoryStream stream = new MemoryStream (ASCIIEncoding.Default.GetBytes(rtf));
rtb_wording.SelectAll();
rtb_wording.Selection.Load(stream, DataFormats.Rtf);
}

Categories