Reputation: 33
My program uses stacks to check if a programming statement or a formula has balanced parenthesis. everything works except for the life of me I can't seem to find a way to Highlight and unbalanced pair of Parens in the same textbox it was entered into when I push my button to check for Parens.
Here is my code for reference:
private void btnCheckParens_Click(object sender, EventArgs e)
{
Stack leftParens = new Stack();
Stack rightParens = new Stack();
string expression = txtParens.Text;
string ch;
int indexOfParens;
for ( int i = 0; i < expression.Length; i++)
{
ch = expression.Substring(i,1);
if (isParenthesis(ch))
{
if (ch == "(")
leftParens.Push(ch);
else
rightParens.Push(ch);
}
}
if (!(leftParens.Count == rightParens.Count))
{
if (leftParens.Count > rightParens.Count)
{
indexOfParens = expression.LastIndexOf("(");
txtParens.SelectionStart = indexOfParens;
txtParens.SelectionLength = 1;
}
else
indexOfParens = expression.LastIndexOf(")");
txtParens.SelectionStart = indexOfParens;
txtParens.SelectionLength = 1;
}
else
MessageBox.Show("Number of parens are balanced!","success");
}
static bool isParenthesis(string ch) { bool flag; if ( ch == "(" || ch == ")") flag = true; else flag =false; return flag; }
Upvotes: 0
Views: 1868
Reputation: 244752
Fendy posted the solution in a comment:
Set the focus to textbox first using
txtParens.Focus();
The reason that you have to do this is because Windows controls do not (by default) display the current selection unless they have the focus. This applies to textboxes, too.
You can verify this for yourself in the Run dialog. When it is first opened, the "Open" textbox has the focus and any text that it contains is selected and highlighted. However, if you press the Tab key to move the focus to one of the buttons along the bottom, the selection highlight immediately disappears. The text in the textbox is still selected (and will be highlighted again if you Tab back), but the selection is not highlighted because the control has lost the focus.
You can change this behavior by modifying the value of the HideSelection
property, which you can either do in the designer using the Properties Window or through code:
txtParens.HideSelection = false;
Setting HideSelection
to true uses the default behavior: the selected text does not appear highlighted when the control loses focus. Setting it to false
ensures that the selected text always remains highlighted, even when the control loses focus.
Upvotes: 1