Right and Left alignment richtextbox c# - c#

I wanna make a box where I can display certain text left oriented and certain text right oriented in C#.
For example,
Code
If (msg from admin)
richTextBox.Append(rightAligned(msg))
else
richTextBox.Append(leftAligned(msg))
I tried SelectionAlignment feature of richTextBox, but it applies particular format for all the text in the box. How can I achieve desired result? Any help would be greatly appreciated.

You can use Environment.Newline and RichTextBox.SelectionAlignment for your richTextBox.
For Example:
if (msg from admin) {
richTextBox.AppendText(Environment.NewLine + msg);
richTextBox.SelectionAlignment = HorizontalAlignment.Right;
} else {
richTextBox.AppendText(Environment.NewLine + msg);
richTextBox.SelectionAlignment = HorizontalAlignment.Left;
}

This Could be done as well :)
If (...)
{
textBox1.TextAlign = HorizontalAlignment.Left;
textBox1.Text = " Blah Blah ";
}
else
{
textBox1.TextAlign = HorizontalAlignment.Right;
textBox1.Text = " Blah Blah Right";
}

To just set the alignment of the appended text, you need to select just the appended text, then use the SelectionAlignment property:
public static void AppendLineAndAlignText(this RichTextBox richTextBox, string text, HorizontalAlignment alignment)
{
if (string.IsNullOrEmpty(text))
return;
var index = richTextBox.Lines.Length; // Get the initial number of lines.
richTextBox.AppendText("\n" + text); // Append a newline, and the text (which might also contain newlines).
var start = richTextBox.GetFirstCharIndexFromLine(index); // Get the 1st char index of the appended text
var length = richTextBox.Text.Length;
richTextBox.Select(start, length - index); // Select from there to the end
richTextBox.SelectionAlignment = alignment; // Set the alignment of the selection.
richTextBox.DeselectAll();
}
After testing a bit, it seems that just setting the SelectionAlignment will work as long as the text string contains no newline characters, but if there are embedded newlines, only the last appended line gets aligned correctly.
public static void AppendLineAndAlignText(this RichTextBox richTextBox, string text, HorizontalAlignment alignment)
{
// This only works if "text" contains no newline characters.
if (string.IsNullOrEmpty(text))
return;
richTextBox.AppendText("\n" + text); // Append a newline, and the text (which must not also contain newlines).
richTextBox.SelectionAlignment = alignment; // Set the alignment of the selection.
}

You want to use RichTextBox.SelectionAlignment. Shamelessly stolen from another SO answer.
It appears you will have to append the text, select it and then change SelectionAlignment.

Related

getting position of input string then get substring on both ends

I have a search function that searches keywords in a block of text and displays a truncated version of the results. My problem is that it will not show the searched keyword if its near the end.
For example.
Text = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or blockquotes on a Web page. Often times, the text takes on the shape of a square or rectangular block"
I search for "times" with
text = text.Substring(0, 100) + "...";
It will return
"A block of text is text that is grouped together in some way, such as with the use of paragraphs or..."
Is there a way to return 100 characters before and after the searched keyword?
You can do this,
string s = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or";
string toBeSearched = "grouped";
int firstfound = s.IndexOf(toBeSearched);
if (firstfound != -1 )
{
string before = s.Substring(0 , firstfound);
string after = s.Substring(firstfound + toBeSearched.Length);
}
DEMO
string s = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or";
string wordtoSearch = "block";
int firstfound = s.IndexOf(wordtoSearch);
// If the index of the first letter found is greater than 100, get the 100 letters before the found word and 100 letters after the found word
if (firstfound > 100)
{
string before = s.Substring(firstfound , firstfound-100);
string after = s.Substring(firstfound + wordtoSearch.Length, 100);
Console.WriteLine(before);
Console.WriteLine(after);
}
//// If the index of the first letter found is less than 100, get the letters before the found word and 100 letters after the found word
if(firstfound < 100)
{
string before = s.Substring(0, firstfound);
Console.WriteLine(before);
if(s.Length >100)
{
string after = s.Substring(firstfound + wordtoSearch.Length, 100);
Console.WriteLine(after);
}
else
{
string after = s.Substring(firstfound + wordtoSearch.Length);
Console.WriteLine(after);
}
}
You can do something like this as well, making it a bit more reusable and able to match multiple instances of the keyword
string input = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or blockquotes on a Web page. Often times, the text takes on the shape of a square or rectangular block";
int buffer = 30; // how much do you want to show before/after
string match = "times";
int location = input.IndexOf(match);
while (location != -1) {
// take buffer before and after:
int start = location - Math.Min (buffer , location); // don't take before start
int end = location + match.Length
+ Math.Min( buffer, input.Length - location - match.Length); // don't take after end
Console.WriteLine("..." + input.Substring(start, end-start) + "...");
location = input.IndexOf(match,location+1);
}
Giving you an output of
...A block of text is text that is gro...
...with the use of paragraphs or blockquotes on a Web page. Often ...
...pe of a square or rectangular block...

How to move the cursor in multiline textbox from the end of the line to the beginning of the next one?

I have a multiline textbox with wordwrap on, while I want it's cursor to be located in the beginning of the next line when it arrives at the end of the current one.
e.g. - if 8 characters can be entered in line (monospaced), and I enter this:
12345678
I would like the cursor to be under the '1' char (and not after the 8).
The challenge is: I can't use NewLine as a part of the textbox string.
You could subscribe for notifications when the textbox changes, and if there's 8 characters add an Environment.NewLine to the text. After the first line you'd have to do a split on the text to only get the last line but that's not too hard. The user will always be able to manually move the cursor to the end of the line again though so you'd need to add logic to check if there are 9 characters on the line and delete the last one.
The thing that finally solved my problem, while taking into account the limitation of NOT using Environment.NewLine was adding one more additional space, save the SelectionStart position, and calculate the correct one without considering the redundant space (see another post about How to make wordwrap consider a whitespace in a string as a regular character?)
This solution fits for a very special case in which I've created my own "NewLine" for our use which will occur while the user will click Alt+Enter - The amount of relevant spaces will be added to fill a line (then I needed the cursor to go down... this was the issue!):
private void TextBox_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
var tb = sender as TextBox;
if (Keyboard.Modifiers == ModifierKeys.Alt && Keyboard.IsKeyDown(Key.Enter))
{
int origSelectionStart = tb.SelectionStart;
int paddingSpacesAmountToAdd = WidthInCells - (tb.Text.Substring(0, tb.SelectionStart)).Length%WidthInCells;
int origPaddingSpacesAmountToAdd = paddingSpacesAmountToAdd;
// Only if the cursor is in the end of the string - add one extra space that will be removed eventually.
if (tb.SelectionStart == tb.Text.Length) paddingSpacesAmountToAdd++;
string newText = tb.Text.Substring(0, tb.SelectionStart) + new String(' ', paddingSpacesAmountToAdd) + tb.Text.Substring(tb.SelectionStart + tb.SelectionLength);
tb.Text = newText;
int newSelectionPos = origSelectionStart + origPaddingSpacesAmountToAdd;
tb.SelectionStart = newSelectionPos;
e.Handled = true;
}
else if (Keyboard.IsKeyDown(Key.Enter))
{
//source already updated because of the binding UpdateSourceTrigger=PropertyChanged
e.Handled = true;
}
}
That won't be enough (as I mentioned above - there's a spaces issue), so:
void _textBox_TextChanged(object sender, TextChangedEventArgs e)
{
int origCursorLocation = _textBox.SelectionStart;
// Regular Whitespace can't be wrapped as a regular character, thus - we'll replace it.
_textBox.Text.Replace(" ", "\u00A0");
_textBox.SelectionStart = origCursorLocation;
}
Important - This solution works for MonoSpace characters when there's a calculation of the exact fitting fontsize.

C# Cursor/ Caret Not display when Append text in Richtextbox

I am new to Programming, i am making C# Windows Form Application were, on selecting Tree node, it append the text in Richtextbox:
Qs1: For me Caret is not displayed after selecting the tree Node.
Qs2: Make display like editor, where if word start with // ( Comment) should be in green color.
Thanks
if (treeView1.SelectedNode.Name == "Node1")
{
this.richTextBox1.SelectedText += " my text for Node1" + Environment.NewLine
richTextBox1.Focus();
}
else if (treeView1.SelectedNode.Name == "Node2")
{
this.richTextBox1.SelectedText += " my text for Node2" + Environment.NewLine
richTextBox1.Focus();
}
You're asking two questions related to RichTextBox. The preferred form on StackOverflow is one question per question. You'll probably get more responses with more focused questions.
That being said:
According to the documentation for the Select method:
The text box must have focus in order for the caret to be moved.
So you need to do that first.
In addition, as a general rule, you should never modify the pre-existing Text or SelectedText with += because this will clear away any and all RTF formatting on that text. Instead, to insert text, you should set the selection to the desired location, with length zero, and insert there. Thus:
public static void FocusAndAppendToSelectedText(this RichTextBox richTextBox, string text)
{
Action append = () =>
{
richTextBox.Focus();
var start = richTextBox.SelectionStart;
var length = richTextBox.SelectionLength;
var insertAt = start + length;
richTextBox.Select(insertAt, 0);
richTextBox.SelectedText = text;
};
if (richTextBox.InvokeRequired)
richTextBox.BeginInvoke(append);
else
append();
}
Also, you should use \n rather than Environment.Newline because the latter will get simplified into the former anyway.
A question like "[How to] Make display like editor, where if word start with // ( Comment) should be in green color" is very general. Try to break it down into discrete issues and ask questions for those you can't figure out yourself. To get you started, see this question here: highlight the '#' until line end in richtextbox. However, you may want to set the SelectionBackColor not the SelectionColor, depending on your precise UI requirements.

Rich Text to Plain Text via C#?

I have a program that reads through a Microsoft Word 2010 document and puts all text read from the first column of every table into a datatable. However, the resulting text also includes special formatting characters (that are usually invisible in the original Word document).
Is there a way that I can take the string of text that I've read and strip all the formatting characters from it?
The program is pretty simple, and uses the Microsoft.Office.Interop.Word assemblies. Here is the main loop where I'm grabbing the text from the document:
// Loop through each table in the document,
// grab only text from cells in the first column
// in each table.
foreach (Table tb in docs.Tables)
{
for (int row = 1; row <= tb.Rows.Count; row++)
{
var cell = tb.Cell(row, 1);
var listNumber = cell.Range.ListFormat.ListString;
var text = listNumber + " " + cell.Range.Text;
dt.Rows.Add(text);
}
}
EDIT: Here is what the text ("1. Introduction") looks like in the Word document:
This is what it looks like before being put into my datatable:
And this is what it looks like when put into the datatable:
So, I'm trying to figure out a simple way to get rid of the control characters that seem to be appearing (\r, \a, \n, etc).
EDIT: Here is the code I'm trying to use. I created a new method to convert the string:
private string ConvertToText(string rtf)
{
using (RichTextBox rtb = new RichTextBox())
{
rtb.Rtf = rtf;
return rtb.Text;
}
}
When I run the program, it bombs with the following error:
The variable rtf, at this point, looks like this:
RESOLUTION: I trimmed the unneeded characters before writing them to the datatable.
// Loop through each table in the document,
// grab only text from cells in the first column
// in each table.
foreach (Table tb in docs.Tables)
{
for (int row = 1; row <= tb.Rows.Count; row++)
{
var charsToTrim = new[] { '\r', '\a', ' ' };
var cell = tb.Cell(row, 1);
var listNumber = cell.Range.ListFormat.ListString;
var text = listNumber + " " + cell.Range.Text;
text = text.TrimEnd(charsToTrim);
dt.Rows.Add(text);
}
}
I don't know exactly what formatting you're trying to remove, but you could try something like:
text = text.Where(c => !Char.IsControl(c)).ToString();
That should strip the non-printing characters out.
Al alternative can be that You need to add a rich textbox in your form (you can keep it hidden if you don't want to show it) and when you have read all your data just assign it to the richtextbox. Like
//rtfText is rich text
//rtBox is rich text box
rtBox.Rtf = rtfText;
//get simple text here.
string plainText = rtBox.Text;
Why dont you give this a try:
using System;
using System.Text.RegularExpressions;
public class Example
{
static string CleanInput(string strIn)
{
// Replace invalid characters with empty strings.
try {
return Regex.Replace(strIn, #"[^\w\.#-]", "",
RegexOptions.None, TimeSpan.FromSeconds(1.5));
}
// If we timeout when replacing invalid characters,
// we should return Empty.
catch (RegexMatchTimeoutException) {
return String.Empty;
}
}
}
Here's a link for it as well.
http://msdn.microsoft.com/en-us/library/844skk0h.aspx
Totally different approach would be to look at the Open Office XML SDK.
This example should get you started.

Changing background color of words in richTextBox after typing a special character

Using the richTextBox control, how to change in real time the background color of words that are separated by a comma, and put a blank space instead of the comma? A bit like the keywords' presentation of Stackoverflow.
Here you have a small code red-colouring the background when certain word ("anything") is written in a richtextbox. I hope that this will be enough to help you understand how to interact with a richtextbox at runtime. Bear in mind that it is pretty simplistic: it colours "anything" only if it is first word you introduce; and stops coloring if you write any other character after it.
int lastStart = 0;
int lastEnd = 0;
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
richTextBox1.Select(lastStart, lastEnd + 1);
if (richTextBox1.SelectedText.ToLower() == "anything")
{
richTextBox1.SelectionBackColor = Color.Red;
lastStart = richTextBox1.SelectionStart + richTextBox1.SelectionLength;
}
else
{
richTextBox1.SelectionBackColor = Color.White;
}
lastEnd = richTextBox1.SelectionStart + richTextBox1.SelectionLength;
richTextBox1.Select(lastEnd, 1);
}
The following string: "One, Two, Three, Four" can be converted to a list of strings with the items "One" - "Two" - "Three" - "Four" with the following code:
string FullString = "One, Two, Three, Four";
Regex rx = new Regex(", ");
List<string> ListOfStrings = new List<string>();
foreach (string newString in rx.Split(FullString))
{
ListOfStrings.Add(newString);
}
Regarding the color you can take a look here:
Rich Text Box how to highlight text block
To be able to do this in realtime I suggest you use the TextChanged event for the RTB and from there you can call a function changing the color.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged.aspx
When this is done you can use the String.Replace(char, char) function to remove the comas and change them to blank spaces.
http://msdn.microsoft.com/en-us/library/czx8s9ts.aspx

Categories

Resources