您好,登錄后才能下訂單哦!
本文實(shí)例講述了C#使用RichTextBox實(shí)現(xiàn)替換文字及改變字體顏色功能。分享給大家供大家參考,具體如下:
替換文字
private void GenerateEntity() { try { string result = ChangeWords("specific content..."); txtContent.Text = result; ChangeColor(); } catch (Exception ex) { MessageBox.Show("類生成失??!錯(cuò)誤信息:" + ex.Message); } } private string ChangeWords(string content) { //先替換"nvarchar"、"varchar"、"nchar",再替換"char" //不然"nvarchar"、"varchar"、"nchar"就會被替換為 //nvarstring"、"varstring"、"nstring"不能進(jìn)行原有規(guī)則替換 string result = Regex.Replace(content, "nvarchar", "string"); //進(jìn)行下一步替換的時(shí)一定要以上一步替換的返回結(jié)果為數(shù)據(jù)源而不是content //因?yàn)閏ontent值沒有改變 result = Regex.Replace(result, "varchar", "string"); result = Regex.Replace(result, "nchar", "string"); result = Regex.Replace(result, "char", "string"); result = Regex.Replace(result, "tinyint", "int"); result = Regex.Replace(result, "smallint", "int"); result = Regex.Replace(result, "bigint", "int"); result = Regex.Replace(result, "datetime", "DateTime"); return result; }
改變字體顏色
要改變字體顏色一定要使用RichTextBox,普通的文本框不能實(shí)現(xiàn)為某些特殊文字添加顏色的功能。
private void ChangeColor() { txtContent.SelectionStart = 0; txtContent.SelectionLength = txtContent.Text.Length; txtContent.SelectionColor = Color.Black; //列注釋不為空時(shí),改變列注釋顏色 if (listDescription.Count > 0) { ChangeKeyColor(listDescription, Color.Green); } ChangeKeyColor("namespace", Color.Blue); ChangeKeyColor("public", Color.Blue); ChangeKeyColor("class", Color.Blue); ChangeKeyColor("http:/// <summary>",Color.Gray); ChangeKeyColor("http:///", Color.Gray); ChangeKeyColor("http:/// </summary>", Color.Gray); ChangeKeyColor("int", Color.Blue); ChangeKeyColor("double", Color.Blue); ChangeKeyColor("float", Color.Blue); ChangeKeyColor("char", Color.Blue); ChangeKeyColor("string", Color.Blue); ChangeKeyColor("bool", Color.Blue); ChangeKeyColor("decimal", Color.Blue); ChangeKeyColor("enum", Color.Blue); ChangeKeyColor("const", Color.Blue); ChangeKeyColor("struct", Color.Blue); ChangeKeyColor("DateTime", Color.CadetBlue); ChangeKeyColor("get",Color.Blue); ChangeKeyColor("set", Color.Blue); } public void ChangeKeyColor(string key, Color color) { Regex regex = new Regex(key); //找出內(nèi)容中所有的要替換的關(guān)鍵字 MatchCollection collection = regex.Matches(txtContent.Text); //對所有的要替換顏色的關(guān)鍵字逐個(gè)替換顏色 foreach (Match match in collection) { //開始位置、長度、顏色缺一不可 txtContent.SelectionStart = match.Index; txtContent.SelectionLength = key.Length; txtContent.SelectionColor = color; } } public void ChangeKeyColor(List<string> list, Color color) { foreach (string str in list) { ChangeKeyColor(str, color); } }
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#常見控件用法教程》、《C#窗體操作技巧匯總》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》及《C#程序設(shè)計(jì)之線程使用技巧總結(jié)》
希望本文所述對大家C#程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。