public static List <IToken> SyntaxHighlight(FastColoredTextBox textbox) { List <IToken> tokens; // TODO: This is slow on a large DAX expression and may cause flickering... //textbox.SuspendDrawing(); // Doesn't work as we might be on a different thread try { var lexer = new DAXLexer(new DAXCharStream(textbox.Text, Preferences.Current.UseSemicolonsAsSeparators)); lexer.RemoveErrorListeners(); tokens = lexer.GetAllTokens().ToList(); } catch { textbox.ClearStyle(StyleIndex.All); return(new List <IToken>()); } textbox.BeginInvoke((MethodInvoker)(() => { textbox.SuspendDrawing(); textbox.ClearStyle(StyleIndex.All); foreach (var tok in tokens) { if (tok.Type == DAXLexer.Eof) { break; } var range = textbox.GetRange(tok.StartIndex, tok.StopIndex + 1); if (tok.Channel == DAXLexer.KEYWORD_CHANNEL) { range.SetStyle(KeywordStyle); } else if (tok.Channel == DAXLexer.COMMENTS_CHANNEL) { range.SetStyle(CommentStyle); } else { switch (tok.Type) { case DAXLexer.INTEGER_LITERAL: case DAXLexer.REAL_LITERAL: case DAXLexer.STRING_LITERAL: range.SetStyle(LiteralStyle); break; case DAXLexer.OPEN_PARENS: case DAXLexer.CLOSE_PARENS: range.SetStyle(ParensStyle); break; default: range.SetStyle(PlainStyle); break; } } } textbox.ResumeDrawing(); })); return(tokens); }
/// <summary> /// Performs replace /// </summary> /// <param name="original"></param> /// <param name="updated"></param> private void DoReplace(string original, string updated) { E.BeginInvoke(new MethodInvoker(() => { ProjectFile.ReplaceSymbol(original, updated); })); if (!IsDisposed) { Close(); } }
/// <summary> /// RichTextBox自动补全 /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> public static void FastColoredTextBoxTextChangedVoid(object obj1, object obj2) { if (th != null) { th.Abort(); th = null; } FastColoredTextBox rtb = (FastColoredTextBox)obj1; string result = ""; string text = rtb.Text; string startText = text.Substring(0, rtb.SelectionStart); string endtext = ""; string selectText = ""; if (rtb.SelectionStart != text.Length) { endtext = text.Replace(startText, ""); } string[] array = System.Text.RegularExpressions.Regex.Split(startText, @"\s{1,}"); if (array.Length >= 1) { selectText = array[array.Length - 1]; } else { selectText = ""; } if (th == null) { th = new System.Threading.Thread((System.Threading.ThreadStart) delegate { Form1 f; Point p = winApi.CaretPos(); f = new Form1(selectText, textlist, new Point(p.X + 10, p.Y + 20)); try { if (!f.IsDisposed) { Application.Run(f); result = f.result; if (result != "") { rtb.BeginInvoke(new Action(() => { startText = startText.Substring(0, startText.Length - selectText.Length) + result; //处理 rtb.Text = startText + endtext; rtb.SelectionStart = startText.Length; //增加后的光标位置 })); } } } catch (Exception ex) { f.Close(); } }); th.SetApartmentState(ApartmentState.STA); th.IsBackground = true; th.Start(); } }
/// <summary> /// Colorizes the tokens. /// </summary> /// <param name="editor">The editor.</param> /// <param name="registry">The registry.</param> /// <param name="tokens">The tokens.</param> /// <param name="errorTokens">The error tokens.</param> public void ColorizeTokens(FastColoredTextBox editor, IStyleRegistry registry, IList <SyntaxToken> tokens, IList <IToken> errorTokens) { int coloring = Interlocked.Exchange(ref _TokenColoringInProgress, 1); if (coloring != 0) { return; } editor.BeginInvoke( new MethodInvoker(() => { editor.BeginUpdate(); try { foreach (var token in tokens) { var startingPlace = new Place(token.ActualParserToken.Column, token.ActualParserToken.Line - 1); var stoppingPlace = new Place(token.EndingColumnPosition, token.EndingLineNumber - 1); var tokenRange = editor.GetRange(startingPlace, stoppingPlace); tokenRange.ClearStyle(StyleIndex.All); var style = registry.GetTokenStyle(token); tokenRange.SetStyle(style); } foreach (var token in errorTokens) { var startingPlace = new Place(token.Column, token.Line - 1); var endPlace = token.GetEndPlace(); // We shift the end position one forward so that the range colors correctly. var stoppingPlace = new Place(endPlace.Position + 1, endPlace.Line - 1); var tokenRange = editor.GetRange(startingPlace, stoppingPlace); tokenRange.SetStyle(registry.GetParseErrorStyle()); } } // ReSharper disable once CatchAllClause catch (Exception ex) { var errorDisplay = new ErrorDisplay { Text = Resources.TokenColoringErrorTitle, ErrorMessage = ex.Message, ErrorStackTrace = ex.StackTrace }; errorDisplay.ShowDialog(); } finally { editor.EndUpdate(); } _TokenColoringInProgress = 0; })); }
/// <summary> /// 显示sql自定义查询错误信息 /// </summary> /// <param name="c"></param> /// <param name="error"></param> /// <param name="rand"></param> public void tabPageErrorShow(SkinTabPage c, string error, string rand = "") { try { if (!RunSqlList.ContainsKey(rand)) { return; } //不包含返回 Models.RunSqlForm rsf = RunSqlList[rand]; if (rsf.datagridview != null) { foreach (Control control in c.Controls) { if (control.Name == "datagridview" + rand) { c.Controls.Remove(control); } } // rsf.datagridview.Controls.Clear(); } string errorFctb = "errorfctb" + rand;//当前错误框唯一name if (rsf.errorFctb != null) { foreach (Control control in c.Controls) { if (control.Name == errorFctb) { c.Controls.Remove(control); } } // rsf.datagridview.Controls.Clear(); } FastColoredTextBox fctb = new FastColoredTextBox();//输入框 fctb.Name = errorFctb; fctb.Location = new Point(10, c.Height / 2); fctb.Language = Language.SQL; //sql fctb.Width = c.Width - 30; //控件宽度 fctb.Height = 300; //控件高度 fctb.ImeMode = ImeMode.On; //开启 c.Controls.Add(fctb); rsf.errorFctb = fctb; rsf.datagridview = null; //指定为null RunSqlList[rand] = rsf; //重新赋值 fctb.BeginInvoke(new Action(() => { fctb.Multiline = true; fctb.WordWrap = true; error = error.Substring(0, error.IndexOf('在')); fctb.Text = error; fctb.Language = Language.CSharp;//xml })); } catch (Exception ex) { pLogs.logs(ex.ToString()); } }
void OpenTab( string path ) { foreach ( FATabStripItem page in _TabControl1.Items ) if ( page.Tag is string ) if ( ( string )page.Tag == path ) { _TabControl1.SelectedItem = page; return; } FATabStripItem faTabStripItem = new FATabStripItem( ); faTabStripItem.Title = Path.GetFileName( path ); FastColoredTextBox RB1 = new FastColoredTextBox( ); #region TextBox Properties RB1.Dock = DockStyle.Fill; RB1.CurrentLineColor = Color.FromArgb( 255, 255, 64 ); RB1.BackColor = Color.FromArgb( 70, 70, 70 ); RB1.ForeColor = Color.White; RB1.PreferredLineWidth = 0; RB1.BorderStyle = BorderStyle.FixedSingle; RB1.Cursor = Cursors.IBeam; RB1.ChangedLineColor = Color.DarkRed; RB1.ChangedLineWidth = 2; RB1.LeftBracket = '['; RB1.LeftBracket2 = '('; RB1.LeftBracket3 = '{'; RB1.RightBracket = ']'; RB1.RightBracket2 = ')'; RB1.RightBracket3 = '}'; RB1.BracketsStyle = RB1.BracketsStyle2 = RB1.BracketsStyle3 = new MarkerStyle( new SolidBrush( Color.FromArgb( 0, 160, 160 ) ) ); RB1.SelectionStyle.BackgroundBrush = new SolidBrush( preferencesWindow.colors[ 4 ] ); RB1.Font = preferencesWindow.f; RB1.BorderStyle = BorderStyle.None; RB1.IndentBackColor = Color.FromArgb( 120, 120, 120 ); RB1.LineNumberColor = Color.FromArgb( 225, 225, 225 ); #endregion bool iswait = true; RB1.TextChanged += new EventHandler<TextChangedEventArgs>( ( object sender, TextChangedEventArgs e ) => { new Thread( new ThreadStart( ( ) => { if ( !RB1.IsHandleCreated ) return; faTabStripItem.Saved = false; _TabControl1.BeginInvoke( new MethodInvoker( ( ) => { _TabControl1.Invalidate( ); } ) ); if ( RB1.BackColor != Color.FromArgb( 50, 50, 50 ) ) RB1.BackColor = Color.FromArgb( 50, 50, 50 ); RB1.BeginInvoke( new MethodInvoker( ( ) => { new Thread( new ThreadStart( ( ) => { try { string txt = RB1.Text; List<Token> lineStream = tokenizer.Tokenize( new Range( RB1, 0, RB1.Selection.Start.iLine == 0 ? 0 : RB1.Selection.Start.iLine - 1, RB1.Lines[ RB1.Selection.Start.iLine == RB1.LinesCount - 1 ? RB1.Selection.Start.iLine : RB1.Selection.Start.iLine + 1 ].Length, RB1.Selection.Start.iLine == RB1.LinesCount - 1 ? RB1.Selection.Start.iLine : RB1.Selection.Start.iLine + 1 ).Text , RB1.Selection.Start.iLine == 0 ? 1 : RB1.Selection.Start.iLine ); Lexer.Lexing( ref lineStream ); PaintTextBox( RB1, lineStream ); try { RB1.TabLength = int.Parse( preferencesWindow.tab_spaces.Text ); RB1.TabLength = 4; if ( iswait ) System.Threading.Thread.Sleep( int.Parse( preferencesWindow.paint_delay.Text ) ); else iswait = true; } catch { MessageBox.Show( this, "Fix code editor at preferences window \r\nPath: File->Preferences->Scripts and codes" ); return; } if ( RB1.Text != txt ) return; RB1.VisibleRange.ClearStyles( false ); RB1.VisibleRange.ClearFoldingMarkers( false ); List<Token> lt = tokenizer.Tokenize( RB1.VisibleRange.Text ); Lexer.Lexing( ref lt ); PaintTextBox( RB1, lt ); } catch { MessageBox.Show(this, "Exception caught while painting" ); } } ) ).Start( ); } ) ); } ) ).Start( ); } ); RB1.KeyDown += new KeyEventHandler( ( object sender, KeyEventArgs kea ) => { RB1.SelectionStyle.BackgroundBrush = new SolidBrush( preferencesWindow.colors[ 4 ] ); RB1.Font = preferencesWindow.f; //runningForm.savedProject = false; int speccount = 0; bool isstr = false; int ind = RB1.Selection.Start.iChar; List<Char> txt = RB1[ RB1.Selection.Start.iLine ]; txt.ForEach( new Action<Char>( ( Char c ) => { if ( --ind <= -1 ) return; if ( c.c == '"' || c.c == '\'' ) isstr = isstr == false; } ) ); if ( isstr ) return; string astr = RB1.Text.Substring( 0, RB1.SelectionStart ); int startline = astr.LastIndexOf( '\n', RB1.SelectionStart - 1 ); if ( startline == -1 ) startline = 0; string astr2 = astr.Substring( startline ); if ( kea.KeyValue == 219 && kea.Shift ) { kea.Handled = true; RB1.InsertText( " {\r\n" + new string( ' ', RB1[ RB1.Selection.Start.iLine ].StartSpacesCount + RB1.TabLength ) ); iswait = false; RB1.OnTextChanged( ); } else if ( kea.KeyValue == 8 && RB1.SelectionStart > 0 && RB1.SelectionLength == 0 ) { astr = RB1.Text; startline = astr.LastIndexOf( '\n', RB1.SelectionStart - 1 ) + 1; if ( astr.Substring( startline, RB1.SelectionStart - startline ) == new string( ' ', RB1.SelectionStart - startline ) ) { speccount = RB1.SelectionStart - startline; if ( startline != 0 ) speccount += 2; RB1.SelectionStart -= speccount; RB1.SelectionLength = speccount; RB1.SelectedText = ""; kea.Handled = true; } } else if ( kea.KeyValue == 13 ) { int spaces = RB1[ RB1.Selection.Start.iLine ].StartSpacesCount; if ( RB1.Selection.CharAfterStart == '\n' ) return; RB1.InsertText( "\r\n" + new string( ' ', spaces ) ); kea.Handled = true; } else if ( kea.KeyValue == 221 && kea.Shift ) { kea.Handled = true; int spaces = RB1[ RB1.Selection.Start.iLine ].StartSpacesCount; if ( astr2.Replace( " ", "" ) == "\n" ) { if ( astr2.Length > RB1.TabLength + 1 ) { RB1.SelectionStart -= RB1.TabLength; RB1.SelectionLength = RB1.TabLength; RB1.SelectedText = "}\r\n" + new string( ' ', spaces - RB1.TabLength ); } else { RB1.SelectionStart = startline + 1; RB1.SelectionLength = astr2.Length - 1; RB1.SelectedText = "}\r\n"; } } else { if ( spaces < RB1.TabLength + 1 ) { RB1.InsertText( "\r\n}\r\n" + new string( ' ', spaces ) ); } else { RB1.InsertText( "\r\n" + new string( ' ', spaces - RB1.TabLength ) + "}\r\n" + new string( ' ', spaces - RB1.TabLength ) ); } } } } ); RB1.Text = File.ReadAllText( path ); RB1.Height = RB1.Width = 2500; faTabStripItem.Controls.Add( RB1 ); faTabStripItem.Tag = path; _TabControl1.Items.Add( faTabStripItem ); List<Token> lt2 = tokenizer.Tokenize( RB1.Text ); Lexer.Lexing( ref lt2 ); PaintTextBox( RB1, lt2 ); RB1.OnTextChanged( ); RB1.ClearLineChanges( ); faTabStripItem.Saved = true; OpenTab( path ); _TabControl1.Invalidate( ); }
public void InvokeOnUIThread(ColorizeMethod colorize) { TextBox.BeginInvoke(new MethodInvoker(colorize)); }
/// <summary> /// 动态sql生成查询 /// </summary> /// <param name="hash"></param> public void createSqlRunTab(string hash) { try { string[] array = hash.Split('|'); string text = ""; Dictionary <string, string> database = new Dictionary <string, string>(); if (array.Length <= 0) { return; } if (array.Length == 1)//查询主数据库 { Data.pDataManageClass p = new Data.pDataManageClass(); string dataHash = array[0]; database = p.getDataBaseHash(array[0]); array = new string[4]; array[0] = dataHash; array[1] = "database"; array[2] = database["type"]; } if (array[2] == Data.DataBaseType.Mysql.ToString())//mysql { if (array.Length > 2) { text = array[3]; if (array[1] == "database") { text = database["name"]; } } } ContextMenuStrip cms = new ContextMenuStrip(); //关闭右键菜单 Random rd = new Random(); cms.Items.Add("关闭" + text); //添加右键文本 string rand = rd.Next(10000, 99999).ToString(); string name = text + rand; SkinTabPage page = new SkinTabPage(); page.ToolTipText = Text + " 查询"; //提示显示完整 page.Text = text + " 查询"; //tab显示文本 page.Name = name; //tab name 唯一 page.ContextMenuStrip = cms; cms.Name = "cms" + rand; cms.ItemClicked += closeTabPage;//关联事件 this.skinTabControl1.Controls.Add(page); Label lab = new Label(); lab.Text = text + " 查询"; lab.Location = new Point(10, 5); page.Controls.Add(lab); SkinButton skbutton = new SkinButton(); skbutton.Text = "查询"; skbutton.Name = "sqlrun" + rand; skbutton.Click += getRunSql;//点击事件 skbutton.Location = new Point(10, 30); page.Controls.Add(skbutton); FastColoredTextBox fctb = new FastColoredTextBox();//输入框 fctb.Name = "fctb" + rand; fctb.Location = new Point(10, 80); fctb.Language = Language.SQL; //sql fctb.Width = page.Width - 30; //控件宽度 fctb.Height = page.Height / 3; //控件高度 fctb.ImeMode = ImeMode.On; //开启 fctb.KeyDown += RunSqlKeysDown; //键盘事件 fctb.BorderStyle = BorderStyle.FixedSingle; //边框 page.Controls.Add(fctb); //添加输入框 skinTabControl1.SelectedTab = page; //指定tabpage显示 if (array.Length == 5) //打开表查询 { fctb.BeginInvoke(new Action(() => { string table = array[4]; fctb.Text = string.Format("select *from {0}", table); })); } Models.RunSqlForm rsf = new Models.RunSqlForm { button = skbutton, fctb = fctb, stp = page, selectHash = hash, }; if (!RunSqlList.ContainsKey(rand)) { RunSqlList.Add(rand, rsf);//添加列队 } else { RunSqlList[rand] = rsf; } } catch (Exception ex) { pLogs.logs(ex.ToString()); } }
protected override void Append(LoggingEvent loggingEvent) { if (_richTextBox == null) { if (string.IsNullOrEmpty(FormName) || string.IsNullOrEmpty(TextBoxName)) { return; } Form form = Application.OpenForms[FormName]; if (form == null) { return; } _richTextBox = FindControlRecursive(form, TextBoxName) as FastColoredTextBox; if (_richTextBox == null) { return; } form.FormClosing += (s, e) => _richTextBox = null; } lock (_richTextBox) { // This check is required a second time because this class // is executing on multiple threads. if (_richTextBox == null) { return; } // Because the logging is running on a different thread than // the GUI, the control's "BeginInvoke" method has to be // leveraged in order to append the message. Otherwise, a // threading exception will be thrown. Action <FastColoredTextBox, string> del = new Action <FastColoredTextBox, string>((_richTextBox, s) => { //some stuffs for best performance _richTextBox.BeginUpdate(); _richTextBox.Selection.BeginUpdate(); //remember user selection Range userSelection = _richTextBox.Selection.Clone(); //add text with predefined style _richTextBox.TextSource.CurrentTB = _richTextBox; _richTextBox.AppendText("=======================================================\n", styles[loggingEvent.Level.Name]); _richTextBox.AppendText(s, styles[loggingEvent.Level.Name]); _richTextBox.AppendText("=======================================================\n", styles[loggingEvent.Level.Name]); //restore user selection if (!userSelection.IsEmpty || userSelection.Start.iLine < _richTextBox.LinesCount - 2) { _richTextBox.Selection.Start = userSelection.Start; _richTextBox.Selection.End = userSelection.End; } else { _richTextBox.GoEnd(); //scroll to end of the text } // _richTextBox.Selection.EndUpdate(); _richTextBox.EndUpdate(); } ); _richTextBox.BeginInvoke(del, _richTextBox, loggingEvent.RenderedMessage + Environment.NewLine); } }