Enter button does not work at textbox - c#

I'm a beginner in c# and first time need your help, because I can't find any solution to this problem.
I make a typewriting tutorial, I have a richtextbox filled with randomly generated characters, spaces and 3 new line.
The user must type the characters in a textbox, and if he typed the adequate character the character turn to green in richtextbox and he can type the the next one. If he makes a mistake, he cant move to next character until the the right button was pressed.
My problem is everything works, except new line part.
When the program compare the 2 new line accept the new line but just when ctrl+enter was pressed, simple enter wont work, the program somehow thinks enter is a wrong character.
I need to make this user friendly and a simple enter needed for this.
I tried this so far:
Make textbox MultiLine makes no difference.
Changed Acceptsreturn to true makes no difference.
Changed in string that will be the text of richtextbox the Environment.Newline to \r and \n and \r\n and its makes no difference.
Changed the textbox to Richtextbox makes no difference.
I tried every possible combination above and I cant work out what is the problem.
Here it is the random character generating part:
public partial class Form1 : Form
{
char[] karakterek = { 'a','á','b','c','d','e','é','f','g','h','i','í','j','k','l','m','n','o','ó','ö','ő','p','q','r','s','t','u','ú','ü','ű','v','x','y','z' };
char[] nemkarakterek = {'0','1','2','3','4','5','6','7','8','9','"',',','+','%','/','=',':','-',};
char egykarakter;
string teljes = "";
int mutato = 0;
Random r = new Random();
public Form1()
{
InitializeComponent();
karakterfeltolt();
}
private void karakterfeltolt()
{
int hanyszor = 0;
do
{
string egesz = "";
if (hanyszor < 3)
{
do
{
if (egesz.Length < 150)
{
if (r.Next(1,15)<14)
{
egykarakter = karakterek[r.Next(0, karakterek.Length)];
egesz = egesz + egykarakter;
}
else
{
egykarakter = nemkarakterek[r.Next(0, nemkarakterek.Length)];
egesz = egesz + egykarakter;
}
}
} while (egesz.Length < 150);
if (egesz.Length > 150)
{
egesz = egesz.Substring(0, 150);
}
int vanespace = 0;
egesz = egesz.Insert(r.Next(2, 10), " ");
for (int i = 0; i < egesz.Length - 10; i++)
{
if (egesz[i] == ' ')
{
vanespace = i;
int eselynovelo = r.Next(0, 10);
if (eselynovelo > 6)
{
egesz = egesz.Insert(r.Next(vanespace + 3, vanespace + 10), " ");
}
else
{
egesz = egesz.Insert(r.Next(vanespace + 6, vanespace + 10), " ");
}
}
}
string nagybetus = egesz.Substring(0, 1).ToUpper() + egesz.Substring(1);
nagybetus = nagybetus.Insert(nagybetus.Length, ".\r\n");
teljes = teljes + nagybetus;
hanyszor++;
}
} while (hanyszor < 3);
richTextBox1.Text = teljes;
}
And here is the textbox compare part:
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == richTextBox1.Text[mutato])
{
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = mutato + 1;
richTextBox1.SelectionColor = Color.Green;
mutato++;
label2.Text = "OK";
}
else
{
label2.Text = "Wrong";
e.Handled = true;
}
}
What else can I do? Please help me.

Related

Hint system to tell a random false selection

I'm making a c# windows form application in which there are five buttons each corresponding to a number 1-5 and the user guesses a random number out of those. I need to implement a hint which would tell the user a random false selection. How would I do this?
public partial class frmGuessANumber : Form
{
int number;
public frmGuessANumber()
{
InitializeComponent();
Random rnd = new Random();
number = rnd.Next(1, 6);
}
private void SelectionMade(object sender, EventArgs e)
{
Button selection = (Button)sender;
int guess = Convert.ToInt32(selection.Text);
if (guess == number)
{
DisableButtons();
lblMessage.Text = "Congratulations! " + guess + " is correct!";
lblMessage.Visible = true;
}
else
{
DisableButtons();
lblMessage.Text = "Sorry! " + guess + " isn't the right answer.";
lblMessage.Visible = true;
}
}
private void lblHint_MouseHover(object sender, EventArgs e)
{
Random rnd = new Random();
int wrongSelection = rnd.Next(2, 6);
if (number == 1)
lblHint.Text = "The number is not " + wrongSelection;
else
lblHint.Text = "The number is not " + (number - 1);
}
private void DisableButtons()
{
btnGuess1.Enabled = false;
btnGuess2.Enabled = false;
btnGuess3.Enabled = false;
btnGuess4.Enabled = false;
btnGuess5.Enabled = false;
}
}
You could
1) enumerate the possible numbers using Enumerable.Range
2) then take all except the correct solution (in your case number). You can use the Where method
3) then you would randomly pick a number from this set as a hint. You can use the ElementAt method
Random rnd = new Random();
int CorrectAnswer = rnd.Next(1, 6);
int hint = Enumerable.Range(1,6).Where(x=>x != CorrectAnswer ).ElementAt(rnd.Next(1,5));
Since the user has been deleted, I will just leave the answer for future people with a similar problem:

Why looping twice on string length test

I'm working in C# (2013) Windows Forms. My instructor wanted us to ensure that the txtStateInput is upperCase when we hit the calculate button. However when I input a two character string such as "wi" and then hit calculate, it throws the message "enter valid state" and clears out the textbox. When I enter the "wi" in a second time then it works. I can't figure out why this is happening, the code would lead me to believe that it would check to ensure the string in txtStateInput is two characters and then when calculate is clicked it would uppercase the string. I can't figure out why it only works once I enter in the state "wi" a second time.
private void btnCalc_Click(object sender, EventArgs e)
{
//declare variables.
int startPop = 0;
int endPop = 0;
string Message = "Error";
decimal Percent = 0.0m;
string State = "";
string City = String.Empty;
int dTimes = 0;
try
{
City = txtCityInput.Text;
//System Globalization was initialized so this method works.
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
txtCityInput.Text = myTI.ToTitleCase(City);
if(txtStateInput.Text.Length != 2)
{
MessageBox.Show("Enter valid State");
txtStateInput.Focus();
txtStateInput.SelectAll();
}
else
{
State = txtStateInput.Text.ToUpper();
txtStateInput.Text = State;
if ((int.TryParse(txtStartPopInput.Text, out startPop)) && int.TryParse(txtEndPopInput.Text, out endPop))
{
if ((startPop > 0) && (endPop > 0))
{
//if population has decreased.
if ((startPop > endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Decrease of " + Percent.ToString("p");
}
//if population has increased.
if ((startPop < endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Increase of " + Percent.ToString("p");
}
//if population has not changed.
if ((startPop == endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "No Change in Population";
}
}
else
{
MessageBox.Show("Please enter valid population figures.");
}
}
if (int.TryParse(txtDisplayTimes.Text, out dTimes))
{
if (dTimes > 0)
{
lstResults.Items.Clear();
int iSum = 0;
int iLoopCount = dTimes;
//displays the results according to value in txtDisplayTimes.
for (iSum = 1; iSum <= iLoopCount; iSum++)
{
lstResults.Items.Add(Message);
}
}
}
}
}
catch
{
MessageBox.Show("Something went wrong.");
}
}

Hyperlink to a line of RichTextBox in C#

I am looking a way to create a HyperLink in a RichTextBox pointing to a line of the text of the same RichTextBox.
I just found how to do that with Internet Links but I don't find a way to do it with the same text inside of the control (It's like Hyperlinks in MS Word pointing to a header or bookmark).
Thanks in Advance. - CCB
No, this will not work unless you code the necessary stuff yourself.
Two suggestions:
A simple workaround with links always starting with www.
The nicer solution with arbitrary link text
Let's have a look at both options..:
Using the built-in functionality of recognizing an URL seems the right way to start, but the link will always have to look like a URL, not like a hyperlink to an anchor.. If you can live with a solution that has, say, links like this: www.goto.234 and anchors like this: #234# this is really rather simple..
A working example can be as simple as this:
private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
var s = e.LinkText.Split('.');
string anchor = s[2];
int a = richTextBox1.Text.IndexOf("#" + anchor + "#" );
if (a >= 0) richTextBox1.SelectionStart = a; else return; // do add more checks!
richTextBox1.SelectionLength = 0;
Text = anchor + " # " + a;
//richTextBox1.ScrollToCaret(); <<--- this crashes on my machine!
// so I take the jump out of the click event and it works:
Timer ttt = new Timer() { Interval = 100 };
ttt.Tick += (ss, ee) => { richTextBox1.ScrollToCaret(); ttt.Stop(); };
}
Option two: If you'd rather have more choice of how the links should read you can do this:
Start by formatting each to
Start with a special character, say a tilde '~'
format it to look blue and underlined if you want to
Either make it one word or replace space by underlines and format those to have the forecolor equal to the backcolor
Now this can do the job:
public string delimiters = " ()[]{}!&?=/\\,;.\r\n";
private void richTextBox2_Click(object sender, EventArgs e)
{
int sstart = -1;
string s = getWordAt(richTextBox2.Text,
richTextBox2.SelectionStart, delimiters, out sstart);
if (s.Length < 3) return;
string char1 = s.Substring(0, 1);
if (char1 == "~")
{
int p = richTextBox2.Text.IndexOf("#" + s.Substring(1));
if (p >= 0) { richTextBox2.SelectionStart = p; richTextBox2.ScrollToCaret(); }
}
}
public static string getWordAt(string text, int cursorPos,
string delimiters, out int selStart)
{
int startPos = 0;
selStart = startPos;
if ((cursorPos < 0) | (cursorPos > text.Length) | (text.Length == 0)) return "";
if ((text.Length > cursorPos) & (delimiters.Contains(text[cursorPos]))) return "";
int endPos = text.Length - 1;
if (cursorPos == text.Length) endPos = text.Length - 1;
else { for (int i = cursorPos; i < text.Length; i++)
{ if (delimiters.Contains(text[i])) { endPos = i - 1; break; } } }
if (cursorPos == 0) startPos = 0;
else { for (int i = cursorPos; i > 0; i--)
{ if (delimiters.Contains(text[i])) { startPos = i + 1; break; } } }
selStart = startPos;
return text.Substring(startPos, endPos - startPos + 1);
}
Here are the two versions side by side, once at the top then after clicking on a link:
Both versions work fine, although both could do with some more checks.
Note that I was too lazy to format the pseudo-links in the second example, so they show their tildes and hashes..
Not hard to write a helper function that can insert the formatting; the search will still work as it searches in the Text, not the Rtf property..

Copy paste from a text box adds extra lines

So basically I have a button that takes the strings delimited by line breaks in one text box that then formats them a particular way and puts them in a different text box. Everything looks fine when I run the code, however, when I copy and paste the text from the second textbox to a different place, it adds a line break after everything that I took from the original box.
private void ToTableButton_Click(object sender, EventArgs e)
{
StringBuilder tableText = new StringBuilder();
string[] lines = BasicTextBox.Text.Split('\n');
TableTextBox.Clear();
try
{
for (int i = 0; i < columnsUpDown.Value; i++)
{
if (i == columnsUpDown.Value - 1)
{
tableText.Append(lines[i]);
}
else
{
tableText.Append(lines[i] + " | ");
}
}
tableText.Append(Environment.NewLine);
for (int i = 0; i < columnsUpDown.Value; i++)
{
if (i == columnsUpDown.Value - 1)
{
tableText.Append("--");
}
else
{
tableText.Append("--|");
}
}
int currentPos = Convert.ToInt32(columnsUpDown.Value);
while (currentPos <= lines.Length)
{
tableText.Append(Environment.NewLine);
for (int i = 0; i < columnsUpDown.Value; i++)
{
if (i == columnsUpDown.Value - 1)
{
tableText.Append(lines[currentPos]);
}
else
{
tableText.Append(lines[currentPos] + " | ");
}
currentPos++;
}
}
}
catch
{
}
TableTextBox.Text = tableText.ToString();
}
I thought maybe this be because the split doesn't remove the \n but I wasn't sure how to remove it afterwards. Any advice would be greatly appreciated.
I would think that trimming the lines[currentPos] would be the correct way...
tableText.Append(lines[currentPos].ToString().Trim());

How Can I Prevent RichTextBox Append which Can Cause OutOfMemory?

My Objective is keep logs line by line with RichtextBox control, But I am worry that when the lines reach to certain point , my window form will be hung or run of out memory..
Can any one show me how can i prevent this will happen, I have in mind maybe limit 300 lines with FIFO , or 500 lines then empty and refresh again..However i am not sure How Can i implement this.
void WriteLog(string txt)
{
richTextBox1.AppendText(txt + Environment.NewLine);
richTextBox1.HideSelection = false;
richTextBox1.SelectionStart = richTextBox1.Text.Length;
}
If you want to delete lines than try to use this
void WriteLog(string txt)
{
if(richTextBox1.Lines.Count() == 100)
{
DeleteLine(0);
}
richTextBox1.AppendText(txt + Environment.NewLine);
richTextBox1.HideSelection = false;
richTextBox1.SelectionStart = richTextBox1.Text.Length;
}
private void DeleteLine(int a_line)
{
int start_index = richTextBox1.GetFirstCharIndexFromLine(a_line);
int count = richTextBox1.Lines[a_line].Length;
// Eat new line chars
if (a_line < richTextBox1.Lines.Length - 1)
{
count += richTextBox1.GetFirstCharIndexFromLine(a_line + 1) -
((start_index + count - 1) + 1);
}
richTextBox1.Text = richTextBox1.Text.Remove(start_index, count);
}
try this code to remove last line and then append text then you'll have just 300lines limit:
private void RemoveLastLineAfter300()
{
if(richTextBox1.TextLength != 0)
{
int totalCharacters = richTextBox1.Text.Trim().Length;
int totalLines = richTextBox1.Lines.Length;
string lastLine = richTextBox1.Lines[totalLines - 1] + "\n";
string copyOfLastLine = richTextBox1.Lines[totalLines - 1];
if(totalLines > 300)
{
string newstring = richTextBox1.Text.Substring(0, totalCharacters - lastLine.Length);
richTextBox1.Text = newstring;
}
}
}
And if you want to clear text(if I undertood correctly) after 500lines just check on TextChanged event
if(richTextBox1.Lines.Length > 500)
richTextBox1.Text = string.Empty;
I hope this helps you.

Categories