|
Good work, but performance is really bad. Renders it useless for any document larger than 100 lines.
|
|
|
|
|
He already mentioned that in the known issues.
|
|
|
|
|
Looks like ForeColor doesnt work for this control, So i have black background and need to change color of text because it is black by default. :/ BTW CTRL+Z and CTRL+Y are broken, don't work.
|
|
|
|
|
Hi! I am Modding the DLL. When i finish modding. I will send you the DLL file.
|
|
|
|
|
|
I Just want to know that this example can arrange the input text automatically just like the Visual Studio?
|
|
|
|
|
Lots and lots of work.. I don't think this is a feat you should perform in C#, but hey..
|
|
|
|
|
I found this example is really useful for me and thank you
|
|
|
|
|
Hi. Great job! I have a question, How can I add block comments, for example en C# I can do this
/*
THIS IS A BLOC COMMENT
*/
But I don't know how can I implement this using your work.
|
|
|
|
|
Both the source code and the demo do not work in VB2008
I did the conversion but it doesn't work. Have you made any update since then?
|
|
|
|
|
I want to add HTML tags to keywords, but it didn't highlighting. How can I do it?
|
|
|
|
|
First, your SyntaxRichTextBox is fantastic work!
But i got some trouble to compile keywords with a backslash in it.
Like
.Keywords.Add("\pard")
.Keywords.Add("\par")
....
RTF code got only keywords with a backslash in it.
I try to fix this issue by myself, but if u want to add this would be great.
Best regards
Member 8350898
|
|
|
|
|
Use
@ before the string to make sure the backslashes get to the string, or remove backslashes.
|
|
|
|
|
Hello.
Downloaded the source and demo. When I load the demo into Visual Studio 2010 it does
convert it.
Then, if I try to display the MainForm.cs it says :
Could not find type 'SyntaxHighlighter.SyntaxRichTextBox'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built using settings for your current platform or Any CPU.
The variable 'm_syntaxRichTextBox' is either undeclared or was never assigned.
|
|
|
|
|
Here again. I need to use the character ! ( for !Include) but I can't find the way the library allow it in the library. Can you tell me how to allow this kind of characters, or any other, in code? Thanks in advance!
|
|
|
|
|
I'm planning a free NSIS editor that reads all included files looking inside .vbp ans .SLN project files to generate a NSIS script. This editor saved me a lot of time. Thank you Patrik!
|
|
|
|
|
Hi,
what about multi-line comments ? this is not implemented.
--[[
Multi-line comment 1
Multi-line comment 2
]]
Domi.
|
|
|
|
|
//Hi everybody, I modified the source code in order to produce a code and sql editor. Here is my code.
//Please any enhancement let me know at: aaron.ibanez@godcorporation.com
//-----------------------------------------------------------------------------------------
using DbMappingFactoryCodeGen.CodeGen;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DbMappingFactoryCodeGen.CodeEditor
{
public class CodeEditorTextBox : RichTextBox
{
private readonly Dictionary<languageeditortype, keyword=""> m_Keywords = new Dictionary<languageeditortype, keyword="">()
{
{
LanguageEditorType.CSharp, new Keyword(){
HighlightKewords = @"\b(abstract|as|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|" +
@"foreach|get|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|" +
@"set|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|volatile|void|while|System.DateTime|#region|#endregion)\b",
HighlightKewordsColor = Color.Blue,
HighlightComments = @"(@(?:""[^""]*"")+|""(?:[^""\n\\]+|\\.)*""|'(?:[^'\n\\]+|\\.)*')|//.*|/\*(?s:.*?)\*/",
HighlightCommentsColor = Color.Green,
CaseSensitive = true,
HighlightNumbers = "\\b(?:[0-9]*\\.)?[0-9]+\\b",
HighlightNumbersColor = Color.LightGray,
HighlightStrings = "\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"",
HighlightStringsColor = Color.Red
}
},
{
LanguageEditorType.VB, new Keyword() {
HighlightKewords = @"\b(AddHandler|AddressOf|Alias|And|AndAlso|As|Assembly|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|CDec|CDbl|Char|CInt|Class|CLng|CObj|Const|Continue|Compare|CSByte|CShort|CSng|CStr|" +
@"CType|CUInt|CULng|CUShort|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else|ElseIf|End|EndIf|Enum|Erase|Error|Event|Exit|False|Finally|For|Friend|Function|Get|" +
@"GetType|GetXMLNamespace|Global|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|IsNot|Let|Lib|Like|Long|Loop|Me|Mid|Mod|Module|MustInherit|MustOverride|MyBase|MyClass|" +
@"Namespace|Narrowing|New|Next|Not|Nothing|NotInheritable|NotOverridable|Object|Of|On|Operator|Option|Optional|Or|OrElse|Overloads|Overridable|Overrides|ParamArray|Partial|Preserve|Private|Property|" +
@"Protected|Public|RaiseEvent|ReadOnly|ReDim|REM|RemoveHandler|Repeat|Resume|Return|SByte|Select|Set|Shadows|Shared|Short|Single|Static|Step|Stop|Strict|String|Structure|Sub|SyncLock|Then|Throw|To|True|Try|" +
@"TryCast|TypeOf|Variant|Wend|UInteger|ULong|Until|UShort|Using|When|While|Widening|With|WithEvents|#Region|#End Region)\b",
HighlightKewordsColor = Color.Blue,
HighlightComments = @"(^'|'').*?$",
HighlightCommentsColor = Color.Green,
CaseSensitive = false,
HighlightNumbers = "\\b(?:[0-9]*\\.)?[0-9]+\\b",
HighlightNumbersColor = Color.LightGray,
HighlightStrings = "\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"",
HighlightStringsColor = Color.Red
}
},
{
LanguageEditorType.TSql, new Keyword() {
HighlightKewords = @"\b(absolute|action|ada|add|admin|after|aggregate|alias|all|allocate|alter|and|any|are|array|as|asc|asensitive|assertion|asymmetric|at|atomic|authorization|avg|" +
@"backup|before|begin|between|binary|bit|bit_length|blob|boolean|both|breadth|break|browse|bulk|by|call|called|cardinality|cascade|cascaded|case|cast|catalog|char|" +
@"char_length|character|character_length|check|checkpoint|class|clob|close|clustered|coalesce|collate|collation|collect|column|commit|completion|compute|condition|" +
@"connect|connection|constraint|constraints|constructor|contains|containstable|continue|convert|corr|corresponding|count|covar_pop|covar_samp|create|cross|cube|cume_dist|" +
@"current|current_catalog|current_date|current_default_transform_group|current_path|current_role|current_schema|current_time|current_timestamp|current_transform_group_for_type|" +
@"current_user|cursor|cycle|data|database|date|day|dbcc|deallocate|dec|decimal|declare|default|deferrable|deferred|delete|deny|depth|deref|desc|describe|descriptor|destroy|" +
@"destructor|deterministic|diagnostics|dictionary|disconnect|disk|distinct|distributed|domain|double|drop|dump|dynamic|each|element|else|end|end-exec|equals|errlvl|escape|every|" +
@"except|exception|exec|execute|exists|exit|external|extract|false|fetch|file|fillfactor|filter|first|float|for|foreign|fortran|found|free|freetext|freetexttable|from|full|" +
@"fulltexttable|function|fusion|general|get|global|go|goto|grant|group|grouping|having|hold|holdlock|host|hour|identity|identity_insert|identitycol|if|ignore|immediate|in|" +
@"include|index|indicator|initialize|initially|inner|inout|input|insensitive|insert|int|integer|intersect|intersection|interval|into|is|isolation|iterate|join|key|kill|language|" +
@"large|last|lateral|leading|left|less|level|like|like_regex|limit|lineno|ln|load|local|localtime|localtimestamp|locator|lower|map|match|max|member|merge|method|min|minute|mod|" +
@"modifies|modify|module|month|multiset|names|national|natural|nchar|nclob|new|next|no|nocheck|nonclustered|none|normalize|not|null|nullif|numeric|object|occurrences_regex|" +
@"octet_length|of|off|offsets|old|on|only|open|opendatasource|openquery|openrowset|openxml|operation|option|or|order|ordinality|out|outer|output|over|overlaps|overlay|pad|" +
@"parameter|parameters|partial|partition|pascal|path|percent|percent_rank|percentile_cont|percentile_disc|pivot|plan|position|position_regex|postfix|precision|prefix|preorder|" +
@"prepare|preserve|primary|print|prior|privileges|proc|procedure|public|raiserror|range|read|reads|readtext|real|reconfigure|recursive|ref|references|referencing|regr_avgx|" +
@"regr_avgy|regr_count|regr_intercept|regr_r2|regr_slope|regr_sxx|regr_sxy|regr_syy|relative|release|replication|restore|restrict|result|return|returns|revert|revoke|right|" +
@"role|rollback|rollup|routine|row|rowcount|rowguidcol|rows|rule|save|savepoint|schema|scope|scroll|search|second|section|securityaudit|select|sensitive|sequence|session|" +
@"session_user|set|sets|setuser|shutdown|similar|size|smallint|some|space|specific|specifictype|sql|sqlca|sqlcode|sqlerror|sqlexception|sqlstate|sqlwarning|start|state|statement|" +
@"static|statistics|stddev_pop|stddev_samp|structure|submultiset|substring|substring_regex|sum|symmetric|system|system_user|table|tablesample|temporary|terminate|textsize|than|" +
@"then|time|timestamp|timezone_hour|timezone_minute|to|top|trailing|tran|transaction|translate|translate_regex|translation|treat|trigger|trim|true|truncate|tsequal|uescape|under|" +
@"union|unique|unknown|unnest|unpivot|update|updatetext|upper|usage|use|user|using|value|values|var_pop|var_samp|varchar|variable|varying|view|waitfor|when|whenever|where|while|" +
@"width_bucket|window|with|within|without|work|write|writetext|xmlagg|xmlattributes|xmlbinary|xmlcast|xmlcomment|xmlconcat|xmldocument|xmlelement|xmlexists|xmlforest|xmliterate|" +
@"xmlnamespaces|xmlparse|xmlpi|xmlquery|xmlserialize|xmltable|xmltext|xmlvalidate|year|zone)\b",
HighlightKewordsColor = Color.Blue,
HighlightComments = @"(/\*(.|[\r\n])*?\*/)|(--(.*|[\r\n]))",
HighlightCommentsColor = Color.Green,
CaseSensitive = false,
HighlightNumbers = "\\b(?:[0-9]*\\.)?[0-9]+\\b",
HighlightNumbersColor = Color.Gray,
HighlightStrings = "'(?:''|[^']*)*'",
HighlightStringsColor = Color.Red
}
},
{
LanguageEditorType.PlSql, new Keyword() {
HighlightKewords = // Table D-1 PL/SQL Reserved Words
@"\b(ALL|ALTER|AND|ANY|AS|ASC|AT|BEGIN|BETWEEN|BY|CASE|CHECK|CLUSTER|CLUSTERS|COLAUTH|COLUMNS|COMPRESS|CONNECT|CRASH|CREATE|CURRENT|DECLARE|DEFAULT|DELETE|DESC|" +
@"DISTINCT|DROP|ELSE|END|EXCEPTION|EXCLUSIVE|EXISTS|FETCH|FOR|FROM|GOTO|GRANT|GROUP|HAVING|IDENTIFIED|IF|IN|INDEX|INDEXES|INSERT|INTERSECT|INTO|IS|LIKE|LOCK|" +
@"MINUS|MODE|NOCOMPRESS|NOT|NOWAIT|NULL|OF|ON|OPTION|OR|ORDER|OVERLAPS|PRIOR|PROCEDURE|PUBLIC|RESOURCE|REVOKE|SELECT|SHARE|SIZE|SQL|START|TABAUTH|TABLE|THEN|TO|" +
@"UNION|UNIQUE|UPDATE|VALUES|VIEW|VIEWS|WHEN|WHERE|WITH|" +
// Table D-2 PL/SQL Keywords
@"ADD|AGENT|AGGREGATE|ARRAY|ATTRIBUTE|AUTHID|AVG|BFILE_BASE|BINARY|BLOB_BASE|BLOCK|BODY|BOTH|BOUND|BULK|BYTE|CALL|CALLING|CASCADE|CHAR|CHAR_BASE|CHARACTER|CHARSETFORM|" +
@"CHARSETID|CHARSET|CLOB_BASE|CLOSE|COLLECT|COMMENT|COMMIT|COMMITTED|COMPILED|CONSTANT|CONSTRUCTOR|CONTEXT|CONTINUE|CONVERT|COUNT|CURSOR|CUSTOMDATUM|DANGLING|DATA|DATE|" +
@"DATE_BASE|DAY|DEFINE|DETERMINISTIC|DOUBLE|DURATION|ELEMENT|ELSIF|EMPTY|ESCAPE|EXCEPT|EXCEPTIONS|EXECUTE|EXIT|EXTERNAL|FINAL|FIXED|FLOAT|FORALL|FORCE|FUNCTION|GENERAL|" +
@"HASH|HEAP|HIDDEN|HOUR|IMMEDIATE|INCLUDING|INDICATOR|INDICES|INFINITE|INSTANTIABLE|INT|INTERFACE|INTERVAL|INVALIDATE|ISOLATION|JAVA|LANGUAGE|LARGE|LEADING|LENGTH|LEVEL|" +
@"LIBRARY|LIKE2|LIKE4|LIKEC|LIMIT|LIMITED|LOCAL|LONG|LOOP|MAP|MAX|MAXLEN|MEMBER|MERGE|MIN|MINUTE|MOD|MODIFY|MONTH|MULTISET|NAME|NAN|NATIONAL|NATIVE|NCHAR|NEW|NOCOPY|NUMBER_BASE|" +
@"OBJECT|OCICOLL|OCIDATETIME|OCIDATE|OCIDURATION|OCIINTERVAL|OCILOBLOCATOR|OCINUMBER|OCIRAW|OCIREFCURSOR|OCIREF|OCIROWID|OCISTRING|OCITYPE|ONLY|OPAQUE|OPEN|OPERATOR|ORACLE|ORADATA|" +
@"ORGANIZATION|ORLANY|ORLVARY|OTHERS|OUT|OVERRIDING|PACKAGE|PARALLEL_ENABLE|PARAMETER|PARAMETERS|PARTITION|PASCAL|PIPE|PIPELINED|PRAGMA|PRECISION|PRIVATE|RAISE|RANGE|RAW|READ|" +
@"RECORD|REF|REFERENCE|RELIES_ON|REM|REMAINDER|RENAME|RESULT|RESULT_CACHE|RETURN|RETURNING|REVERSE|ROLLBACK|ROW|SAMPLE|SAVE|SAVEPOINT|SB1|SB2|SB4|SECOND|SEGMENT|SELF|SEPARATE|" +
@"SEQUENCE|SERIALIZABLE|SET|SHORT|SIZE_T|SOME|SPARSE|SQLCODE|SQLDATA|SQLNAME|SQLSTATE|STANDARD|STATIC|STDDEV|STORED|STRING|STRUCT|STYLE|SUBMULTISET|SUBPARTITION|SUBSTITUTABLE|" +
@"SUBTYPE|SUM|SYNONYM|TDO|THE|TIME|TIMESTAMP|TIMEZONE_ABBR|TIMEZONE_HOUR|TIMEZONE_MINUTE|TIMEZONE_REGION|TRAILING|TRANSACTION|TRANSACTIONAL|TRUSTED|TYPE|UB1|UB2|UB4|UNDER|UNSIGNED|" +
@"UNTRUSTED|USE|USING|VALIST|VALUE|VARIABLE|VARIANCE|VARRAY|VARYING|VOID|WHILE|WORK|WRAPPED|WRITE|YEAR|ZONE)\b",
HighlightKewordsColor = Color.Chocolate,
HighlightComments = @"(?ms)((? :\s+/\*(?:.(?!\*/))+.\*/)|(?:\s+\-\-[^\r\n]+))*)\s*^\s*([^\-/\s][^;]+;)((? :\s+/\*(?:.(?!\*/))+.\*/)|(?:\s+\-\-[^\r\n]+))*)",
HighlightCommentsColor = Color.Green,
CaseSensitive = false,
HighlightNumbers = "\\b(?:[0-9]*\\.)?[0-9]+\\b",
HighlightNumbersColor = Color.Gray,
HighlightStrings = "'(?:''|[^']*)*'",
HighlightStringsColor = Color.Blue
}
}
};
public LanguageEditorType Language { get; set; }
private static bool m_bPaint = true;
private string m_strLine = "";
private int m_nContentLength = 0;
private int m_nLineLength = 0;
private int m_nLineStart = 0;
private int m_nLineEnd = 0;
private int m_nCurSelection = 0;
///
/// WndProc
///
/// <param name="m" />
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == 0x00f)
{
if (m_bPaint)
base.WndProc(ref m);
else
m.Result = IntPtr.Zero;
}
else
base.WndProc(ref m);
}
///
/// OnTextChanged
///
/// <param name="e" />
protected override void OnTextChanged(EventArgs e)
{
//base.OnTextChanged(e);
// Calculate sh*t here.
m_nContentLength = this.TextLength;
int nCurrentSelectionStart = SelectionStart;
int nCurrentSelectionLength = SelectionLength;
m_bPaint = false;
// Find the start of the current line.
m_nLineStart = nCurrentSelectionStart;
while ((m_nLineStart > 0) && (Text[m_nLineStart - 1] != '\n'))
m_nLineStart--;
// Find the end of the current line.
m_nLineEnd = nCurrentSelectionStart;
while ((m_nLineEnd < Text.Length) && (Text[m_nLineEnd] != '\n'))
m_nLineEnd++;
// Calculate the length of the line.
m_nLineLength = m_nLineEnd - m_nLineStart;
// Get the current line.
m_strLine = Text.Substring(m_nLineStart, m_nLineLength);
this.ProcessAllLines();
m_bPaint = true;
}
///
/// Process a line.
///
private void ProcessLine()
{
// Save the position and make the whole line black
int nPosition = SelectionStart;
SelectionStart = m_nLineStart;
SelectionLength = m_nLineLength;
SelectionColor = Color.Black;
Keyword keyword = this.m_Keywords[Language];
// Process the keywords
this.ProcessRegex(keyword.HighlightKewords, keyword.HighlightKewordsColor, keyword.CaseSensitive);
// Process numbers
this.ProcessRegex(keyword.HighlightNumbers, keyword.HighlightNumbersColor, false);
// Process strings
this.ProcessRegex(keyword.HighlightStrings, keyword.HighlightStringsColor, false);
// Process comments
this.ProcessRegex(keyword.HighlightComments, keyword.HighlightCommentsColor, false);
SelectionStart = nPosition;
SelectionLength = 0;
SelectionColor = Color.Black;
m_nCurSelection = nPosition;
}
///
/// Process a regular expression.
///
/// <param name="strRegex" />The regular expression.
/// <param name="color" />The color.
private void ProcessRegex(string strRegex, Color color, bool caseSensitive)
{
Regex regKeywords = new Regex(strRegex, RegexOptions.Multiline |
(caseSensitive
? RegexOptions.Compiled
: RegexOptions.IgnoreCase | RegexOptions.Compiled));
Match regMatch;
for (regMatch = regKeywords.Match(m_strLine); regMatch.Success; regMatch = regMatch.NextMatch())
{
// Process the words
int nStart = m_nLineStart + regMatch.Index;
int nLenght = regMatch.Length;
SelectionStart = nStart;
SelectionLength = nLenght;
SelectionColor = color;
}
}
///
/// Process all lines
///
public void ProcessAllLines()
{
m_bPaint = false;
int nStartPos = 0;
int i = 0;
int nOriginalPos = SelectionStart;
while (i < Lines.Length)
{
m_strLine = Lines[i];
m_nLineStart = nStartPos;
m_nLineEnd = m_nLineStart + m_strLine.Length;
this.ProcessLine();
i++;
nStartPos += m_strLine.Length + 1;
}
m_bPaint = true;
}
}
public class Keyword
{
public string HighlightKewords { get; set; }
public Color HighlightKewordsColor { get; set; }
public string HighlightComments { get; set; }
public Color HighlightCommentsColor { get; set; }
public bool CaseSensitive { get; set; }
public string HighlightNumbers { get; set; }
public Color HighlightNumbersColor { get; set; }
public string HighlightStrings { get; set; }
public Color HighlightStringsColor { get; set; }
}
public enum LanguageEditorType
{
CSharp = LanguageType.CSharp,
VB = LanguageType.VB,
TSql,
PlSql
}
}
Ing. Aarón Ibáñez Werthermänn
IBM Certified Specialist for RUP
Microsoft Certified Trainer
MCSD .NET, MCAD
|
|
|
|
|
When pressing ctrl+z to undo the changes done to the text, the cursor just jumps to the beginning of the line.
|
|
|
|
|
Just included this with a VS2010 solution, works perfectly for syntax highlighting SQL.
Kevin S. Gallagher
Programming is an art form that fights back
|
|
|
|
|
Did anyone notice the problem that when a block of code is pasted into the Syntaxrickbox, only that last line is processed
m_nContentLength = this.TextLength;
int nCurrentSelectionStart = SelectionStart;
int nCurrentSelectionLength = SelectionLength;
m_bPaint = false;
m_nLineStart = nCurrentSelectionStart;
while ((m_nLineStart > 0) && (Text[m_nLineStart - 1] != '\n'))
m_nLineStart--;
m_nLineEnd = nCurrentSelectionStart;
while ((m_nLineEnd < Text.Length) && (Text[m_nLineEnd] != '\n'))
m_nLineEnd++;
m_nLineLength = m_nLineEnd - m_nLineStart;
m_strLine = Text.Substring(m_nLineStart, m_nLineLength);
ProcessLine();
m_bPaint = true;
|
|
|
|
|
I wanted only unformated text Because I have my editor set to courier. I added this code to paste one line at a time from the clipboard to get all lines processed.
private void m_syntaxRichTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
e.SuppressKeyPress = true;
String textfromclipboard = Clipboard.GetText(System.Windows.Forms.TextDataFormat.Text);
if(textfromclipboard!="")
{
foreach (var myString in textfromclipboard.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
m_syntaxRichTextBox.SelectedText = myString;
m_syntaxRichTextBox.SelectedText = Environment.NewLine;
}
}
}
}
|
|
|
|
|
I am a beginner c # and I'm a chinese.Sorry,My English is so poor.
I think you can write this way:first
write a class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication2
{
public class ChangeColor
{
public void ChangeColorToBlue(string text, Color color, RichTextBox r)
{
int s = 0;
while ((-1 + text.Length - 1) != (s = text.Length - 1 + r.Find(text, s, -1, RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord)))
{
r.SelectionColor = color;
}
}
public void SelectKeyWords(RichTextBox r)
{
int sIndex = r.SelectionStart;
r.SelectAll();
r.SelectionColor = Color.Black;
r.Select(sIndex, 0);
ChangeColorToBlue("static", Color.Blue, r);
ChangeColorToBlue("void", Color.Blue, r);
ChangeColorToBlue("using", Color.Blue, r);
ChangeColorToBlue("if", Color.Blue, r);
ChangeColorToBlue("else", Color.Blue, r);
ChangeColorToBlue("public", Color.Blue, r);
ChangeColorToBlue("private", Color.Blue, r);
ChangeColorToBlue("class", Color.Blue, r);
ChangeColorToBlue("new", Color.Blue, r);
ChangeColorToBlue("int", Color.Blue, r);
ChangeColorToBlue("true", Color.Blue, r);
ChangeColorToBlue("double", Color.Blue, r);
ChangeColorToBlue("is", Color.Blue, r);
ChangeColorToBlue("byte", Color.Blue, r);
ChangeColorToBlue("foreach", Color.Blue, r);
ChangeColorToBlue("struct", Color.Blue, r);
ChangeColorToBlue("while", Color.Blue, r);
ChangeColorToBlue("typeof", Color.Blue, r);
ChangeColorToBlue("float", Color.Blue, r);
ChangeColorToBlue("decimal", Color.Blue, r);
r.Select(sIndex, 0);
r.SelectionColor = Color.Black;
}
}
}
And in Form:
you just use it;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam);
private void button1_Click(object sender, EventArgs e)
{
string fname = GetFileName();
textBox1.Text = fname;
richTextBox1.Text = show(fname);
}
public string GetFileName()
{
string fname = string.Empty;
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = "c:\\";
dlg.Filter = "All files (*.*)|*.*";
dlg.FilterIndex = 1;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
fname = dlg.FileName;
}
return fname;
}
public string show(string fileurl)
{
if (fileurl.Equals(""))
{
return "";
}
else
{
string source = string.Empty;
StreamReader sr = new StreamReader(fileurl, System.Text.Encoding.Default);
string strLine = sr.ReadLine();
while (strLine != null)
{
source += strLine + "\n";
strLine = sr.ReadLine();
}
return source;
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
base.OnTextChanged(e);
SendMessage(base.Handle, 0xB, 0, IntPtr.Zero);
ChangeColor change = new ChangeColor();
change.SelectKeyWords(richTextBox1);
SendMessage(base.Handle, 0xB, 1, IntPtr.Zero);
this.Refresh();
}
}
}
|
|
|
|
|
Thanks this is very helpful and much better than the original code!
I wondered what you can do by now if you were a bigineer when you wrote this piece of code.
|
|
|
|
|
|