C# 高亮显示 指定关键字
在C#程序中,我加了一个SQL执行的功能,用户可以输入简单的SQL,为了区分主要的关键字,同事写了以下程序 ,放在richtextbox控件的textchanged事件中。
//高亮显示指定关键字 private void rtxSql_TextChanged(object sender, EventArgs e) { RichTextBox rtb = sender as RichTextBox; if (rtb == null) return; // 保存当前光标位置和选择状态 int pos = rtb.SelectionStart; int len = rtb.SelectionLength; // SQL关键字列表(不区分大小写) string[] keywords = { "SELECT", "FROM", "WHERE", "GROUP BY", "ORDER BY", "INSERT", "UPDATE", "DELETE", "JOIN", "INNER", "OUTER" }; // 重置所有文本为默认样式 rtb.SelectAll(); rtb.SelectionColor = Color.Black; // 遍历所有关键字进行高亮 foreach (string keyword in keywords) { int index = 0; while (index < rtb.Text.Length) { index = rtb.Text.IndexOf(keyword, index, StringComparison.OrdinalIgnoreCase); if (index < 0) break; rtb.Select(index, keyword.Length); rtb.SelectionColor = Color.Red; index += keyword.Length; } } // 恢复光标位置 rtb.SelectionStart = pos; rtb.SelectionLength = len; }
活到老,学到老。

浙公网安备 33010602011771号