search
HomeBackend DevelopmentC#.Net TutorialDetailed introduction to a .NET code editing control (ICSharpCode.TextEditor)

这篇文章主要给大家介绍了.NET中用ICSharpCode.TextEditor自定义代码折叠与高亮的相关资料,文中通过示例代码与图片介绍的很详细,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

ICSharpCode.TextEditor 是一款非常不错的.NET代码编辑控件,内置了多种高亮语言支持,同时完美支持中文,非常赞!

先来看一下运行效果:

一、项目结构

这里需要注意lib文件夹下导入的类库,这个Demo需要这些dll.

二、代码折叠

需要实现IFoldingStrategy中的 GenerateFoldMarkers 方法,代码如下:

using ICSharpCode.TextEditor.Document;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JackWangCUMT.WinForm
{
 
 /// <summary>
 /// The class to generate the foldings, it implements ICSharpCode.TextEditor.Document.IFoldingStrategy
 /// </summary>
 public class MingFolding : IFoldingStrategy
 {
  /// <summary>
  /// Generates the foldings for our document.
  /// </summary>
  /// <param name="document">The current document.</param>
  /// <param name="fileName">The filename of the document.</param>
  /// <param name="parseInformation">Extra parse information, not used in this sample.</param>
  /// <returns>A list of FoldMarkers.</returns>
  public List<FoldMarker> GenerateFoldMarkers(IDocument document, string fileName, object parseInformation)
  {
   List<FoldMarker> list = new List<FoldMarker>();
   //stack 先进先出
   var startLines = new Stack<int>();
   // Create foldmarkers for the whole document, enumerate through every line.
   for (int i = 0; i < document.TotalNumberOfLines; i++)
   {
    // Get the text of current line.
    string text = document.GetText(document.GetLineSegment(i));

    if (text.Trim().StartsWith("#region")) // Look for method starts
    {
     startLines.Push(i);

    }
    if (text.Trim().StartsWith("#endregion")) // Look for method endings
    {
     int start = startLines.Pop();
     // Add a new FoldMarker to the list.
     // document = the current document
     // start = the start line for the FoldMarker
     // document.GetLineSegment(start).Length = the ending of the current line = the start column of our foldmarker.
     // i = The current line = end line of the FoldMarker.
     // 7 = The end column
     list.Add(new FoldMarker(document, start, document.GetLineSegment(start).Length, i, 57, FoldType.Region, "..."));
    }
    //支持嵌套 {}
    if (text.Trim().StartsWith("{")) // Look for method starts
    {
     startLines.Push(i);
    }
    if (text.Trim().StartsWith("}")) // Look for method endings
    {
     if (startLines.Count > 0)
     {
      int start = startLines.Pop();
      list.Add(new FoldMarker(document, start, document.GetLineSegment(start).Length, i, 57, FoldType.TypeBody, "...}"));
     }
    }


    // /// <summary>
    if (text.Trim().StartsWith("/// <summary>")) // Look for method starts
    {
     startLines.Push(i);
    }
    if (text.Trim().StartsWith("/// <returns>")) // Look for method endings
    {

     int start = startLines.Pop();
     //获取注释文本(包括空格)
     string display = document.GetText(document.GetLineSegment(start + 1).Offset, document.GetLineSegment(start + 1).Length);
     //remove ///
     display = display.Trim().TrimStart(&#39;/&#39;);
     list.Add(new FoldMarker(document, start, document.GetLineSegment(start).Length, i, 57, FoldType.TypeBody, display));
    }
   }

   return list;
  }
 }
}

三、高亮配置

拷贝CSharp-Mode.xshd为 JackCSharp-Mode.xshd ,将其中的名字修改为: SyntaxDefinition name = "JackC#" ,并添加高亮关键字,如下:

这样代码中出现的JackWang就会高亮。下面的代码片段将自定义高亮文件进行加载,并用SetHighlighting进行设置,这里一定注意目录下必须有xshd的配置文件,否则高亮将失效。

textEditor.Encoding = System.Text.Encoding.UTF8;
 textEditor.Font = new Font("Hack",12);
 textEditor.Document.FoldingManager.FoldingStrategy = new JackWangCUMT.WinForm.MingFolding();
 textEditor.Text = sampleCode;

 //自定义代码高亮
 string path = Application.StartupPath+ "\\HighLighting";
 FileSyntaxModeProvider fsmp;
 if (Directory.Exists(path))
 {
  fsmp = new FileSyntaxModeProvider(path);
  HighlightingManager.Manager.AddSyntaxModeFileProvider(fsmp);
  textEditor.SetHighlighting("JackC#");
 }

为了保持代码适时进行折叠,这里监听文本变化,如下所示:

   private void TextEditor_TextChanged(object sender, EventArgs e)
   {
    //更新,以便进行代码折叠
    textEditor.Document.FoldingManager.UpdateFoldings(null, null);
   }

最后说明的是,我们可以定义一个格式化代码的类,来格式化C#代码:

总结

【相关推荐】

1. ASP.NET免费视频教程

2.  ASP.NET教程

3. 极客学院ASP.NET视频教程

The above is the detailed content of Detailed introduction to a .NET code editing control (ICSharpCode.TextEditor). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to use char array in C languageHow to use char array in C languageApr 03, 2025 pm 03:24 PM

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

How to use various symbols in C languageHow to use various symbols in C languageApr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

What is the role of char in C stringsWhat is the role of char in C stringsApr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to handle special characters in C languageHow to handle special characters in C languageApr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

How to convert char in C languageHow to convert char in C languageApr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

Avoid errors caused by default in C switch statementsAvoid errors caused by default in C switch statementsApr 03, 2025 pm 03:45 PM

A strategy to avoid errors caused by default in C switch statements: use enums instead of constants, limiting the value of the case statement to a valid member of the enum. Use fallthrough in the last case statement to let the program continue to execute the following code. For switch statements without fallthrough, always add a default statement for error handling or provide default behavior.

What is the function of C language sum?What is the function of C language sum?Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Advanced C# .NET: Concurrency, Parallelism, and Multithreading ExplainedAdvanced C# .NET: Concurrency, Parallelism, and Multithreading ExplainedApr 03, 2025 am 12:01 AM

C#.NET provides powerful tools for concurrent, parallel and multithreaded programming. 1) Use the Thread class to create and manage threads, 2) The Task class provides more advanced abstraction, using thread pools to improve resource utilization, 3) implement parallel computing through Parallel.ForEach, 4) async/await and Task.WhenAll are used to obtain and process data in parallel, 5) avoid deadlocks, race conditions and thread leakage, 6) use thread pools and asynchronous programming to optimize performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft