private void doCalc() { // get the exact location of cursor int cursorPosition = richTextBox1.SelectionStart; // get the line in question int lineEdited = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart); string[] lines = this.richTextBox1.Text.Split('\n'); string query = ""; if (richTextBox1.SelectionLength == 0) { query = lines[lineEdited]; } else { query = richTextBox1.SelectedText; } Calculation calculation = new Calculation(query); int startOfLine = 0; for (int i = 0; i < lineEdited; i++) { startOfLine += lines[i].Length + 1; } deleteFromStartOfLine(startOfLine); if (!calculation.Error) { writeLineTextBox1(calculation.Query + "\n", Color.Black, FontStyle.Regular); writeLineTextBox1(calculation.Input + " =" + "\n", Color.DarkBlue, FontStyle.Regular); writeLineTextBox1(calculation.Output + " ", Color.DarkGreen, FontStyle.Regular); this.textBox1.Text = calculation.Output; Clipboard.SetText(calculation.Output); this.toolStripStatusLabel1.Text = "Answer copied to clipboard."; } else { writeLineTextBox1(query, Color.DarkRed, FontStyle.Regular); this.textBox1.Text = ""; //Don't show error if there is no query if (calculation.Query.Length == 0) { this.toolStripStatusLabel1.Text = ""; } else { this.toolStripStatusLabel1.Text = calculation.ErrorText; } } richTextBox1.SelectionStart = cursorPosition; //Return cursor to previous position richTextBox1.Focus(); }