I am working with windows form. In my project i need to color the last word of rich text box. When someone write on the given text box of the application i need the last word that is just written on the richtextbox to be colored red or whatever.
I found a way to extract the last word from the following link
http://msdn.microsoft.com/en-us/library/system.windows.documents.textselection.select%28v=vs.95%29.aspx
But i need more handy code to extract the last word if its possible. Please help.
Well, if you really are just looking to get the last word, you could do something like this...Assuming of course, that you make a string equal to the text of your rich text box.
string str="hello, how are you doing?";
if (str.Length >0)
{
int index=str.LastIndexOf(" ") + 1;
str = str.Substring(index));
}
Then just return the string, and do what you need to do with it.
Here is the sample code
*> char[] arr = new char[50];
int i = 0;
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space) {
string str = new string(arr);
MessageBox.Show(str);
Array.Clear(arr, 0, arr.Length);
i = 0;
}
else if (e.KeyCode == Keys.Back)
{
i--;
if (i < 0)
{
i = 0;
}
arr[i] = ' ';
}
else
{
arr[i] = (char)e.KeyValue;
i++;
}
}*
This is how you will be able to extract the latest word. Now color yourself the word you like.
As I remember rich text box can render text as HTML.
Just wrap your last word in font tag and that's it.
Related
I'm trying to make a Reddit Formatter tool for whenever you have a text with just one line break to add another and make a new paragraph. Here in StackOverflow it's the same, you have to press the enter key twice to start a new paragraph. It'd go from:
Roses are red
Violets are Blue
to
Roses are red
Violets are Blue
It's actually pretty easy, and I've managed to do this code below by myself (probably messy, but it works!!) which for the moment replaces the 'a' characters from the textBox to 'e' after pressing a button.
private void button1_Click(object sender, EventArgs e)
{
Char[] textBox1Array = textBox1.Text.ToCharArray();
for (int i = 0; i < textBox1Array.Length; i++)
{
if (textBox1Array[i] == 'a')
{
textBox1Array[i] = 'e';
}
}
textBox1.Text = String.Concat(textBox1Array);
}
The real question is: how do I use the enter key instead of 'a'? HTML code obviously doesn't seem to work:
(
)
and with
\r\n
it throws another error because it doesn't consider it a single character (too many characters in character literal)
A linebreak is not necessarily the same on all systems. So if a user entered his text on Windows the linebreak could lok other than if the text was entered under Linux. So Environment.Newline won't work here. You need to check for several line break types. I would recommend to do the following:
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Replace("\r\n", "\r")
.Replace("\n\r", "\r")
.Replace("\n", "\r")
.Replace("\r", "\r\n\r\n");
}
This way you will replace all (at least the ones I know) possible line break types with a placeholder and then replace that placeholder with a double linebreak (In this case the Windows version).
The straight forward answer would be:
textBox1Array[i] = '\n';
another possibility would be to use the decimal code of new line:
textBox1Array[i] = Convert.ToChar(10);
it will automatically feed back the cursor
You could actually use the string directly without any conversion into an unflexible array. Use a reverse for-loop and access the chars with the [ ] operator, (because string is internally represented as a char-array):
string g = "Roses are red \r\nViolets are Blue";
for (int i = g.Length -1; i >= 0; i--)
{
if (g[i] == '\n')
{
g = g.Insert(i, Environment.NewLine);
// or as a string you can use your former logic
g = g.Insert(i, "\r\n");
}
}
For me it seems the question is about what character stands for enter key, so I'll try answer that.
In my case it was '\r'. To make sure, try this code:
// you need to add textBox1 to try it or just use what's inside the method
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == '\r')
MessageBox.Show("Test");
}
Set a breakpoint on the if line, run the program and press Enter, when it stops on breakline add watch on e and look into its fields. You'll see what character is under e.KeyChar.
What I understand, is that you want where ever your program
intercepts a single newline character it should start a new
paragraph (i.e. "end of a line then a new line + new line).
I suggest two ways to achieve this,
1> On click of a button
2> when user hits the 'Enter/Return' key on keyboard
it should add a new paragraph just like in "MSWord"
For this test, I have put 2 textboxes, TextBox1 , TextBox2,
one command button (btnFormat) that would only work on TextBox1.
following is the code:
private void btnFormat_Click(object sender, EventArgs e)
{
if(String.IsNullOrWhiteSpace(textBox1.Text) == true) return;
//searches for the new line character
Int32 i = textBox1.Text.IndexOf("\r\n");
Int32 j = 0;
if (i == -1) return; //new line character not found
String strA = "";
String strB = "";
//now pass the value in 'i' to 'j'
Int32 icnt = 0;
while(true)
{
//j : from where search should begin. Therefore, it is set
//to a position ahead of last occurence of new line charachter(\r\n)
//i.e. value in 'i'
//i : current occurence of new line character
//scan for the next occurence of new line character from
//current positon
i = textBox1.Text.IndexOf("\r\n",j);
if (i == -1) break;
//there is a possibility of some space(s) or no character at all
//between the last position and current position, then in such a
//case we will remove that newly found new line characters so that
//the formatting is uniform
//all text before new line
strA = textBox1.Text.Substring(0, i);
//all textbox after the new line
strB = textBox1.Text.Substring(i + 2);
if (String.IsNullOrWhiteSpace(textBox1.Text.Substring(j, i - j)) ==
false)
{
textBox1.Text = strA + "\r\n\r\n" + strB;
j = i + 4;
}
else
{
textBox1.Text = strA + strB;
//do not change the value of 'j'
}
}
//increment i and now again scan from this position
//for another new line character
}
Case2:[when entering text or in a previously entered texts]
when user hits the 'Enter/Return' key on keyboard,
like in MSWord, the program automatically start a new paragraph (i.e.
Add two new line characters (\r\n\r\n).
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
e.KeyChar = '\0';//this will suppress current {Return key}
Int32 i = textBox2.SelectionStart;//your current cursor position
String sa = textBox2.Text.Substring(0,i);//text before this pos.
String sb = textBox2.Text.Substring(i);//text beyond from this pos
textBox2.Text = sa + ("\r\n\r\n") + sb;
textBox2.SelectionStart = i + 2;
//if there is already one or more new line characters, then
//this code does not check for that, so it has to be removed
//manually using 'delete' or 'backspace'
}
}
I want to make a clickable text through code in c# (its not a URL just ordinary text) so when i click that text it do linkclicked event.
It is for a dictionary so when I search something and in the description there is a word same from the storage I can click it to search that word.
for (int j = 0; j <= jml[i]; j++)
{
richTextBox4.AppendText(j + 1 + ". ");
string[] desk = sk[i, j].Split(' ');
for (int l = 0; l < desk.Count(); l++)
{
for (int m = 0; m < kata.Count(); m++)
{
if (desk[l] == kata[m])
{
richTextBox4.SelectionColor = Color.Blue;
desk[l] = LinkArea;
}
}
richTextBox4.AppendText(desk[l] + " ");
richTextBox4.SelectionColor = Color.Black;
}
richTextBox4.AppendText("\n");
}
my code for the moment(for the hyperlink type text just the color that work)
There is no built-in way but if you know what you want it is not hard to build.
Step one is to decide just how the clickable text is defined, read: What are the separators?
If you want single words it is rather easy. One way is using a regEx to identify words in a RTB. If you don't like the built-in way to define a word, I can post a code with user-defined separators.. But maybe you are happy with what have already.
If you need whole phrases (including spaces) to be clickable as one whole entity then you will have to be a little more inventive:
either you can add special characters around the phrases
or you can replace the spaces by non-breakable spaces
Or you could write a complete map into your text, but that probably defies your purpose.
Anything but simple words will mean that you will need to apply some changes to your text.
The result should be a function that can find the start and the end of the clickable text and return the clicked word/phrase.
Step Two is to look up the text in a Dictionary<string, string> and do what you want to do with the value, e.g. show the translation in a Label:
if (dictEnGE.ContainsKey(theClickedWord))
label.Text = dictEnGE[theClickedWord];
For this to work you must first prepare the dictionary by adding the key-value pairs: The keys are the clickable texts and the values are whatever you need to find:
Dictionary<string, string> dictEnGE = new Dictionary<string, string>();
dictEnGE.Add("house", "Haus");
dictEnGE.Add("man", "Mann");
dictEnGE.Add("mouse", "Maus");
//..
So the whole solution is: Prepare a dictionary, code the Mouseclick event to find the clicked text, look up the text in the dictioanry, do your thing with the value you find..
Update: Here is a function to get the clicked word:
string getWordAtIndex(RichTextBox RTB, int index)
{
string wordSeparators = " .,;-!?\r\n\"";
int cp0 = index;
int cp2 = RTB.Find(wordSeparators.ToCharArray(), index);
for (int c = index; c > 0; c--)
{ if (wordSeparators.Contains(RTB.Text[c])) { cp0 = c + 1; break; } }
int l = cp2 - cp0;
if (l > 0) return RTB.Text.Substring(cp0, l); else return "";
}
and here is how you could use it:
private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
{
string word = getWordAtIndex(richTextBox1, richTextBox1.SelectionStart);
if (dictEnGE.ContainsKey(word)) aLabel.Text = dictEnGE[word];
}
I have a problem while trying to replace all text matching a particular word in a rich text box. This is the code i use
public static void ReplaceAll(RichTextBox myRtb, string word, string replacer)
{
int index = 0;
while (index < myRtb.Text.LastIndexOf(word))
{
int location = myRtb.Find(word, index, RichTextBoxFinds.None);
myRtb.Select(location, word.Length);
myRtb.SelectedText = replacer;
index++;
}
MessageBox.Show(index.ToString());
}
private void btnReplaceAll_Click(object sender, EventArgs e)
{
Form1 text = (Form1)Application.OpenForms["Form1"];
ReplaceAll(text.Current, txtFind2.Text, txtReplace.Text);
}
This works well but i have noticed a little malfunction when i try to replace a letter with itself and another letter.
For example i want to replace all the e in Welcome to Nigeria with ea.
This is what i get Weaalcomeaaaaaaa to Nigeaaaaaaaaaaaaaaria.
And the message box shows 23 when there are only three e. Pls what am i doing wrong and how can i correct it
Simply do this:
yourRichTextBox.Text = yourRichTextBox.Text.Replace("e","ea");
If you want to report the number of matches (which are replaced), you can try using Regex like this:
MessageBox.Show(Regex.Matches(yourRichTextBox.Text, "e").Count.ToString());
UPDATE
Of course, using the method above has expensive cost in memory, you can use some loop in combination with Regex to achieve some kind of advanced replacing engine like this:
public void ReplaceAll(RichTextBox myRtb, string word, string replacement){
int i = 0;
int n = 0;
int a = replacement.Length - word.Length;
foreach(Match m in Regex.Matches(myRtb.Text, word)){
myRtb.Select(m.Index + i, word.Length);
i += a;
myRtb.SelectedText = replacement;
n++;
}
MessageBox.Show("Replaced " + n + " matches!");
}
im trying to make some kind of search function in my program which is just highlighting all keywords found on textbox
the keyword box is on t2.text and the text is from bx2.text
firstly i tried out this method from here Highlight key words in a given search text
the regex is working but the highlight not
any wrong here?
private void searchs()
{
var spattern = t2.Text;
foreach(var s in bx2.Text)
{
var zxc = s.ToString();
if (System.Text.RegularExpressions.Regex.IsMatch(zxc, spattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
bx2.Text.Replace(bx2.Text, #"<span class=""search-highlight"">$0</span>");
}
}
}
The linked question uses HTML formatting, which you can't use in a regular textbox.
You need either a RichText box. In there you can format text using the control's methods and properties (not using HTML).
Or use a browser control rather than a textbox to use the HTML formatting.
private void findButton_Click(object sender, EventArgs e)
{
int count = 0;
string keyword = keywordTextbox.Text.Trim();//getting given searching string
int startPosition = 0; //initializing starting position to search
int endPosition = 0;
int endArticle = articleRichTextbox.Text.Length;//finding total number of character into the article
for (int i = 0; i<endArticle ; i =startPosition )//creating a loop until ending the article
{
if (i == -1) //if the loop goes to end of the article then stop
{
break;
}
startPosition = articleRichTextbox.Find(keyword, startPosition, endArticle, RichTextBoxFinds.WholeWord);//using find method get the begining position when find the searching string
if (startPosition >= 0) //if match the string //if don't match the string then it return -1
{
count++;//conunting the number of occuerence or match the search string
articleRichTextbox.SelectionColor = Color.Blue;//coloring the matching string in the article
endPosition = keywordTextbox.Text.Length;
startPosition = startPosition + endPosition;//place the starting position at the next word of previously matching string to continue searching.
}
}
if (count == 0)//if the givn search string don't match at any time
{
MessageBox.Show("No Match Found!!!");
}
numberofaccurTextbox.Text = count.ToString();//show the number of occurence into the text box
}
I am trying to have a multi line textbox that when you type in it streams it to the label, BUT the label has to have a max length of 15 so like once it reaches 15 characters in the textbox it should start overwriting the label since it reached it's max length
thanks to anyone who can help
Add onchange event on text box :
if (textBox1.Text.Length<=15)
{
label1.Caption=textBox1.Text;
}
For example
I'm not sure what kind of overwriting You want to achieve.
There are at least three methods you can use:
displaying always the last 15 characters from the textbox, as described in the Olivier's answer
clearing the label's text each 15 characters inserted and start filling in the label over again, you can use this code to achieve this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
String text = textBox1.Text.Replace("\r\n", "|");
int startIndex = ((text.Length - 1) / 15) * 15;
label1.Text = text.Substring(Math.Max(0, startIndex));
}
you can also overwrite char by char when text length is over 15 characters, however, I suppose it's not what you would like to achieve, because it would cause a mess in the textbox ;), however, it can be used as a kind of visual effect :). If you want code snippet for this, let me know :).
Update
Here's the code for the third overwriting method:
String lastText = "";
private void textBox1_TextChanged(object sender, EventArgs e)
{
String textBoxText = textBox1.Text.Replace("\r\n", "|");
if (textBoxText.Length > lastText.Length)
{
int charIndex = (textBoxText.Length - 1) % 15;
if (charIndex >= 0)
{
label1.Text = label1.Text.Insert(charIndex, textBoxText.Substring(textBoxText.Length - 1));
if (charIndex < textBoxText.Length - 1)
{
label1.Text = label1.Text.Remove(charIndex + 1, 1);
}
}
}
else
{
int charIndex = textBoxText.Length % 15;
if (textBoxText.Length >= 15)
{
label1.Text = label1.Text.Insert(charIndex, textBoxText[textBoxText.Length - 15].ToString());
if (charIndex < textBoxText.Length - 1)
{
label1.Text = label1.Text.Remove(charIndex + 1, 1);
}
}
else
{
label1.Text = label1.Text.Remove(label1.Text.Length - 1, 1);
}
}
lastText = textBoxText;
}
Add a handler to the TextChanged event of the TextBox that sets the Label's content based on the text. E.g. (untested, might have your concept wrong or be off by one somewhere)
int startIndex = Math.Max(0, myTextBox.Text.Length - 15);
int endIndex = Math.Min(myTextBox.Text.Length - 1, startIndex);
myLabel.Text = myTextBox.Text.Substring(startIndex, endIndex - startIndex);
Also, though it doesn't change your question/answer, you might want to look at using a TextBlock instead of a Label. It allows things like line wrapping. See some of the differences here: http://joshsmithonwpf.wordpress.com/2007/07/04/differences-between-label-and-textblock/ (in WPF, should be similar whatever you're doing, though)
My solution always displays the last 15 characters in the label
private void textBox1_TextChanged(object sender, EventArgs e)
{
string s = textBox1.Text.Replace("\r\n", "|");
int length = s.Length;
if (length > 15) {
label1.Text = s.Substring(length - 15);
} else {
label1.Text = s;
}
}
I also replace the line-breaks with |. Since your textbox is in multiline mode, line-breaks are entered when you hit <Enter>.