前言:在 Winform 中实现代码高亮是许多开发者和程序员们经常面临的挑战之一。代码高亮可以提升用户对代码的可读性和理解度,使其更易于编写、调试和维护。然而,由于Winform 平台的特殊性,需要一些额外的工作来实现代码高亮功能。
既然直接实现代码高亮很困难,那我们就将网页集成到Winform中来实现,本文主要使用到的插件是WebView2+highlight.js
开发环境:.NET Framework版本:4.8.
开发工具:Visual Studio 2022
实现步骤:
-
首先写一个Html页面,用来集成
highlight.js
实现代码高亮,代码如下<!doctype html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8" />
<meta name="renderer" content="webkit">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/vs2015.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
</head>
<body style="background-color:#000000">
<div>
<pre><code id="codes">Write Your Code</code></pre>
</div>
</body>
</html>
-
Nuget中搜索并下载webView2,以WebView2作为载体加载Html页面,并与Html通信完成代码的实时高亮显示
string htmlPath = Application.StartupPath + "\\code.html";
webView21.CoreWebView2.Navigate(htmlPath);
-
private void textBox1_TextChanged(object sender, EventArgs e)
{
webView21.CoreWebView2.ExecuteScriptAsync($"document.getElementById('codes').innerHTML=`{textBox1.Text}`;hljs.highlightAll();");
}
实现效果: