我正在编写一个c#Html编辑器应用程序,您可以在其中键入RichTextBox控件中的代码。我希望RichTextBox的行为类似于notepad ++和其他代码编辑器,其中Html语法以颜色突出显示,例如:
如何在C#窗口中创建RichTextBox?我几乎到处搜索,没有找到任何帮助我的东西。这是我到目前为止所尝试的但我没有给出我想要的结果:
private void SyntaxHighlight()
{
string[] tags = { "html","head","body","a","b","img","strong","p","h1","h2","h3","h4","h5","h6","embed","iframe","span","form",
"button","input","textarea","br","div","style","script","table","tr","td","th","i","u","link","meta","title"};
foreach (string s in tags)
{
richTextBox1.Find("<" + s);
richTextBox1.SelectionColor = Color.Blue;
richTextBox1.Find(">");
richTextBox1.SelectionColor = Color.Blue;
}
string[] attributes = { "href","src","height","width","rowspan","colspan","target","style","onclick","id","name","class"};
foreach (string s in attributes)
{
richTextBox1.Find(s + "=");
richTextBox1.SelectionColor = Color.Red;
}
}
有人能帮助我吗?我应该在SyntaxHighlight()方法中写什么?有人可以给我适当的代码吗? 谢谢
答案 0 :(得分:3)
在您的代码中,您只能找到第一次出现的HTML标记并突出显示它。但是,您应该遍历整个富文本内容以查找相同文本的后续出现。我刚刚根据您的确切代码进行了快速模拟,请查看。
private void highlightHTMLText()
{
string[] tags = { "html","head","body","a","b","img","strong","p","h1","h2","h3","h4","h5","h6","embed","iframe","span","form",
"button","input","textarea","br","div","style","script","table","tr","td","th","i","u","link","meta","title"};
foreach (string s in tags)
{
findAndHighlight("<" + s, Color.Blue);
findAndHighlight("</" + s, Color.Blue);
findAndHighlight(">", Color.Blue);
}
string[] attributes = { "href", "src", "height", "width", "rowspan", "colspan", "target", "style", "onclick", "id", "name", "class" };
foreach (string s in attributes)
{
findAndHighlight(s + "=", Color.Red);
}
}
private void findAndHighlight(string sSearchStr, Color oColor)
{
int index = richTextBox1.Text.IndexOf(sSearchStr);
while (index != -1)
{
richTextBox1.Select(index, sSearchStr.Length);
richTextBox1.SelectionColor = oColor;
index = richTextBox1.Text.IndexOf(sSearchStr, index + sSearchStr.Length);
}
}
此外,根据this答案,您应该能够使用Notepad ++本身使用的相同实用程序库Scintilla。正如所指出的,你不需要重新发明轮子,但作为开发人员,我显然更喜欢我自己的工具(它只是我;))。希望这会有所帮助。
答案 1 :(得分:0)
查找不移动光标,它返回第一个匹配的位置。试试这个: