c#代码收藏管理器项目
🎯 项目概述
一个功能完整的代码片段收藏管理工具,支持代码的存储、分类、搜索、语法高亮和导入导出。
📁 项目文件结构
核心文件
-
Form1.cs - 主窗体逻辑(1500+行)
-
Form1.Designer.cs - 主窗体界面设计
-
Program.cs - 程序入口点
-
代码收藏.csproj - 项目配置文件
功能类文件
-
LineNumberRichTextBox.cs - 带行号显示的富文本框
-
ImportProgressForm.cs - 导入进度显示窗体
🏗️ 核心架构
1. 数据模型
// 代码片段类
public class CodeSnippet
{
public string Title { get; set; } = "";
public string Code { get; set; } = "";
public string Language { get; set; } = "C#";
public string Description { get; set; } = "";
public string[] Tags { get; set; } = Array.Empty<string>();
public string Category { get; set; } = "未分类";
public DateTime CreatedTime { get; set; }
public DateTime ModifiedTime { get; set; }
}
// 分类类
public class CodeCategory
{
public string Name { get; set; } = "";
public string FullPath { get; set; } = "";
public List<CodeCategory> Children { get; set; } = new List<CodeCategory>();
}
2. 数据存储
-
code_snippets.json - 代码片段数据
-
categories.json - 分类结构数据
✨ 主要功能模块
1. 代码管理功能
-
✅ CRUD操作:新建、保存、更新、删除代码片段
-
✅ 分类管理:树形分类结构,支持添加/删除分类
-
✅ 搜索功能:支持标题、代码、描述、标签、语言的多字段搜索
-
✅ 批量操作:导入、导出功能
2. 语法高亮系统
// 支持的语言
private readonly Dictionary<string, string[]> languageKeywords = new Dictionary<string, string[]>
{
{ "C#", new[] { "abstract", "as", "base", ... } },
{ "Java", new[] { "abstract", "assert", "boolean", ... } },
// ... 支持8种语言
};
// 高亮颜色定义
private readonly Color keywordColor = Color.Blue;
private readonly Color commentColor = Color.Green;
private readonly Color stringColor = Color.Red;
private readonly Color numberColor = Color.Orange;
3. 行号显示功能
-
自定义
Panel实现行号显示 -
实时更新,支持滚动同步
-
右对齐显示,美观易读
4. 文件导入功能
// 支持的文件类型
代码文件|*.cs;*.java;*.py;*.js;*.html;*.htm;*.css;*.sql;*.cpp;*.c;*.h;*.hpp;*.php;*.rb;*.go;*.rs;*.xml;*.json;*.txt
// 导入流程
1. 选择文件 → 2. 显示进度 → 3. 自动识别语言 → 4. 保存到当前分类
5. 导出功能
-
文本格式:结构化文本输出
-
Markdown格式:带代码块的标准Markdown
-
包含完整的元数据信息
🎨 界面设计
布局结构
┌─────────────────┬─────────────────────────────────┐
│ 分类树 │ 标签页控件 │
│ ├─ 所有代码 │ ┌─────────────────────────────┐ │
│ ├─ C# │ │ 编辑代码 │ │
│ ├─ Java │ │ 标题 描述 标签 语言 │ │
│ └─ ... │ │ ┌─行号─┐ 代码编辑区 │ │
│ │ │ │ 1 │ │ │
│ + 添加分类 │ │ │ 2 │ │ │
└─────────────────┘ │ └─────┘ │ │
│ 保存 新建 删除 复制 导入 │ │
└─────────────────────────────┘ │
┌─────────────────────────────┐ │
│ 代码列表 │ │
│ [搜索框] 搜索 │ │
│ ┌─代码片段列表──────────┐ │ │
│ │ 片段1 [C#] - 时间 │ │ │
│ │ 片段2 [Java] - 时间 │ │ │
│ └──────────────────────┘ │ │
│ 详细信息显示区 │ │
└─────────────────────────────┘ │
└─────────────────────────────────┘
控件组成
-
左侧:TreeView(分类) + Panel(分类管理)
-
右侧:TabControl(编辑/列表)
-
编辑页:文本框组 + 代码编辑器 + 操作按钮
-
列表页:搜索框 + ListBox + 详情显示
🔧 技术亮点
1. 事件驱动架构
private void BindEvents()
{
// 按钮事件
btnSave.Click += BtnSave_Click;
btnNew.Click += BtnNew_Click;
// ... 10+个事件绑定
// 编辑器事件
txtCode.TextChanged += TxtCode_TextChanged;
txtCode.VScroll += TxtCode_VScroll;
// 分类事件
treeCategories.AfterSelect += TreeCategories_AfterSelect;
}
2. 语法高亮实现
-
基于正则表达式匹配
-
保存/恢复光标位置
-
错误处理机制
3. 进度反馈
// 导入进度窗体
public void UpdateProgress(int current, string fileName)
{
progressBar.Value = current;
lblStatus.Text = $"正在导入文件 ({current}/{totalFiles})";
lblFileName.Text = fileName;
}
4. 数据持久化
// JSON序列化配置
new JsonSerializerOptions
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
}
🚀 使用技巧
快捷键
-
Ctrl + I:快速导入文件
分类管理
-
支持多级分类(树形结构)
-
删除分类时自动移动代码到"未分类"
-
完整路径存储(如:"所有代码\C#\ASP.NET")
搜索功能
-
多字段搜索(标题、代码、描述、标签、语言)
-
实时过滤显示
-
分类内搜索
🔄 工作流程
添加代码片段
-
选择分类 → 2. 填写信息 → 3. 输入代码 → 4. 保存
导入外部文件
-
点击导入 → 2. 选择文件 → 3. 自动识别 → 4. 批量保存
查找代码
-
选择分类 → 2. 输入关键词 → 3. 查看结果 → 4. 查看详情
📊 性能考虑
-
语法高亮:使用SuspendLayout/ResumeLayout减少闪烁
-
文件操作:异步处理和进度反馈
-
大数据量:虚拟化列表显示
-
错误处理:完善的异常捕获和用户提示
🎯 扩展可能性
-
云同步:添加网络存储支持
-
代码格式化:集成代码美化功能
-
版本控制:代码片段版本历史
-
插件系统:支持自定义高亮规则
-
主题切换:暗色/亮色主题支持
这个项目展示了一个完整的桌面应用程序开发案例,涵盖了UI设计、数据处理、文件操作、文本处理等多个方面,是一个很好的学习参考项目。
完整代码
Form1.cs
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace 代码收藏
{
public partial class Form1 : Form
{
private List<CodeSnippet> codeSnippets;
private string dataFile = "code_snippets.json";
private string categoriesFile = "categories.json";
private int currentEditIndex = -1;
// 语法高亮颜色定义
private readonly Color keywordColor = Color.Blue;
private readonly Color commentColor = Color.Green;
private readonly Color stringColor = Color.Red;
private readonly Color numberColor = Color.Orange;
private readonly Color typeColor = Color.Teal;
private readonly Color normalColor = Color.Black;
// 各语言关键字
private readonly Dictionary<string, string[]> languageKeywords = new Dictionary<string, string[]>
{
{ "C#", new[] { "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", "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", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while", "var", "dynamic", "async", "await", "get", "set", "value", "where", "yield", "partial", "from", "select", "group", "into", "orderby", "join", "let", "by", "ascending", "descending" } },
{ "Java", new[] { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while" } },
{ "Python", new[] { "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield" } },
{ "JavaScript", new[] { "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "export", "extends", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "return", "super", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with", "yield", "let", "await", "async", "static", "enum", "implements", "interface", "package", "private", "protected", "public" } },
{ "C++", new[] { "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char8_t", "char16_t", "char32_t", "class", "compl", "concept", "const", "consteval", "constexpr", "const_cast", "continue", "co_await", "co_return", "co_yield", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq" } },
{ "HTML", new[] { "html", "head", "body", "title", "meta", "link", "script", "style", "div", "span", "p", "h1", "h2", "h3", "h4", "h5", "h6", "a", "img", "ul", "ol", "li", "table", "tr", "td", "th", "form", "input", "button", "select", "option", "textarea", "label", "br", "hr", "nav", "header", "footer", "section", "article", "aside" } },
{ "CSS", new[] { "color", "background", "font", "margin", "padding", "border", "width", "height", "display", "position", "float", "clear", "overflow", "visibility", "opacity", "z-index", "text-align", "vertical-align", "line-height", "font-size", "font-weight", "font-family", "text-decoration", "background-color", "border-radius", "box-shadow", "transition", "animation", "flex", "grid", "align-items", "justify-content" } },
{ "SQL", new[] { "SELECT", "FROM", "WHERE", "INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP", "TABLE", "VIEW", "INDEX", "JOIN", "LEFT", "RIGHT", "INNER", "OUTER", "GROUP BY", "ORDER BY", "HAVING", "DISTINCT", "UNION", "ALL", "AND", "OR", "NOT", "IN", "BETWEEN", "LIKE", "IS", "NULL", "AS", "ON", "SET", "VALUES", "INTO", "DATABASE", "SCHEMA", "TRIGGER", "PROCEDURE", "FUNCTION" } }
};
// 类型关键字
private readonly string[] typeKeywords = new[] { "int", "string", "bool", "float", "double", "decimal", "char", "byte", "short", "long", "object", "dynamic", "var", "void", "List", "Dictionary", "Array", "IEnumerable", "Task" };
public Form1()
{
InitializeComponent();
InitializeCodeEditor();
LoadData();
InitializeSyntaxHighlighting();
BindEvents();
InitializeCategories();
RefreshSnippetList();
}
private void InitializeCodeEditor()
{
// 设置代码编辑器属性
txtCode.Font = new Font("Consolas", 10F);
txtCode.AcceptsTab = true;
txtCode.WordWrap = false;
txtCode.DetectUrls = false;
// 设置行号面板
panelLineNumbers.BackColor = Color.WhiteSmoke;
panelLineNumbers.Paint += PanelLineNumbers_Paint;
}
private void PanelLineNumbers_Paint(object sender, PaintEventArgs e)
{
DrawLineNumbers(e.Graphics);
}
private void DrawLineNumbers(Graphics g)
{
// 填充背景
g.Clear(panelLineNumbers.BackColor);
// 绘制右边框
using (var pen = new Pen(Color.LightGray))
{
g.DrawLine(pen, panelLineNumbers.Width - 1, 0, panelLineNumbers.Width - 1, panelLineNumbers.Height);
}
if (string.IsNullOrEmpty(txtCode.Text))
return;
try
{
// 计算可见行范围
int firstCharIndex = txtCode.GetCharIndexFromPosition(new Point(0, 0));
int firstLine = txtCode.GetLineFromCharIndex(firstCharIndex);
int lastCharIndex = txtCode.GetCharIndexFromPosition(new Point(0, panelCodeContainer.Height));
int lastLine = txtCode.GetLineFromCharIndex(lastCharIndex);
// 确保 lastLine 不超过总行数
int totalLines = txtCode.Lines.Length;
if (lastLine >= totalLines)
lastLine = totalLines - 1;
// 绘制行号
using (var brush = new SolidBrush(Color.Gray))
using (var font = new Font("Consolas", 9F, FontStyle.Regular))
{
int lineHeight = txtCode.Font.Height;
for (int line = firstLine; line <= lastLine + 1; line++)
{
if (line >= totalLines) break;
int lineNumber = line + 1;
// 获取该行的Y坐标
int charIndex = txtCode.GetFirstCharIndexFromLine(line);
if (charIndex < 0) continue;
Point position = txtCode.GetPositionFromCharIndex(charIndex);
if (position.Y < -lineHeight || position.Y > panelCodeContainer.Height) continue;
string lineText = lineNumber.ToString();
// 右对齐显示行号
SizeF textSize = g.MeasureString(lineText, font);
float x = panelLineNumbers.Width - textSize.Width - 5;
float y = position.Y;
g.DrawString(lineText, font, brush, x, y);
}
}
}
catch (Exception ex)
{
// 忽略绘制错误
System.Diagnostics.Debug.WriteLine($"绘制行号错误: {ex.Message}");
}
}
private void UpdateLineNumbers()
{
panelLineNumbers.Invalidate();
}
private void BindEvents()
{
// 按钮事件
btnSave.Click += BtnSave_Click;
btnNew.Click += BtnNew_Click;
btnDelete.Click += BtnDelete_Click;
btnCopy.Click += BtnCopy_Click;
btnExport.Click += BtnExport_Click;
btnSearch.Click += BtnSearch_Click;
btnImport.Click += BtnImport_Click;
// 列表事件
lstSnippets.SelectedIndexChanged += LstSnippets_SelectedIndexChanged;
// 分类相关事件
btnAddCategory.Click += BtnAddCategory_Click;
btnDeleteCategory.Click += BtnDeleteCategory_Click;
treeCategories.AfterSelect += TreeCategories_AfterSelect;
txtNewCategory.KeyPress += TxtNewCategory_KeyPress;
// 语法高亮和行号相关事件
txtCode.TextChanged += TxtCode_TextChanged;
txtCode.VScroll += TxtCode_VScroll;
txtCode.SelectionChanged += TxtCode_SelectionChanged;
cmbLanguage.SelectedIndexChanged += CmbLanguage_SelectedIndexChanged;
// 窗体关闭事件
this.FormClosing += Form1_FormClosing;
}
// 导入文件功能
private void BtnImport_Click(object sender, EventArgs e)
{
ImportFiles();
}
private void ImportFiles()
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Title = "选择要导入的代码文件";
openFileDialog.Multiselect = true;
openFileDialog.Filter = GetFileFilter();
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
ImportSelectedFiles(openFileDialog.FileNames);
}
}
}
private string GetFileFilter()
{
return @"代码文件|*.cs;*.java;*.py;*.js;*.html;*.htm;*.css;*.sql;*.cpp;*.c;*.h;*.hpp;*.php;*.rb;*.go;*.rs;*.xml;*.json;*.txt|" +
@"C# 文件 (*.cs)|*.cs|" +
@"Java 文件 (*.java)|*.java|" +
@"Python 文件 (*.py)|*.py|" +
@"JavaScript 文件 (*.js)|*.js|" +
@"HTML 文件 (*.html;*.htm)|*.html;*.htm|" +
@"CSS 文件 (*.css)|*.css|" +
@"SQL 文件 (*.sql)|*.sql|" +
@"C/C++ 文件 (*.cpp;*.c;*.h;*.hpp)|*.cpp;*.c;*.h;*.hpp|" +
@"PHP 文件 (*.php)|*.php|" +
@"Ruby 文件 (*.rb)|*.rb|" +
@"Go 文件 (*.go)|*.go|" +
@"Rust 文件 (*.rs)|*.rs|" +
@"配置文件 (*.xml;*.json)|*.xml;*.json|" +
@"文本文件 (*.txt)|*.txt|" +
@"所有文件 (*.*)|*.*";
}
private void ImportSelectedFiles(string[] filePaths)
{
if (filePaths == null || filePaths.Length == 0)
return;
int successCount = 0;
int errorCount = 0;
List<string> errorFiles = new List<string>();
// 显示进度对话框
using (var progressForm = new ImportProgressForm(filePaths.Length))
{
progressForm.Show();
for (int i = 0; i < filePaths.Length; i++)
{
string filePath = filePaths[i];
string fileName = Path.GetFileName(filePath);
try
{
progressForm.UpdateProgress(i + 1, fileName);
if (ImportSingleFile(filePath))
{
successCount++;
}
else
{
errorCount++;
errorFiles.Add(fileName);
}
}
catch (Exception ex)
{
errorCount++;
errorFiles.Add($"{fileName} ({ex.Message})");
}
// 让UI有机会更新
Application.DoEvents();
}
progressForm.Close();
}
// 显示导入结果
ShowImportResult(successCount, errorCount, errorFiles);
}
private bool ImportSingleFile(string filePath)
{
try
{
if (!File.Exists(filePath))
return false;
// 读取文件内容
string content = File.ReadAllText(filePath, Encoding.UTF8);
string fileName = Path.GetFileNameWithoutExtension(filePath);
string fileExtension = Path.GetExtension(filePath).ToLower();
// 根据文件扩展名确定语言
string language = GetLanguageFromExtension(fileExtension);
// 获取当前选中的分类
string category = GetCurrentCategory();
// 创建代码片段
var snippet = new CodeSnippet
{
Title = fileName,
Code = content,
Language = language,
Description = $"从文件导入: {Path.GetFileName(filePath)}",
Tags = new[] { "导入", language },
Category = category,
CreatedTime = DateTime.Now,
ModifiedTime = DateTime.Now
};
codeSnippets.Add(snippet);
return true;
}
catch
{
return false;
}
}
private string GetLanguageFromExtension(string extension)
{
return extension.ToLower() switch
{
".cs" => "C#",
".java" => "Java",
".py" => "Python",
".js" => "JavaScript",
".html" or ".htm" => "HTML",
".css" => "CSS",
".sql" => "SQL",
".cpp" or ".c" or ".h" or ".hpp" => "C++",
".php" => "PHP",
".rb" => "Ruby",
".go" => "Go",
".rs" => "Rust",
".xml" => "XML",
".json" => "JSON",
_ => "其他"
};
}
private string GetCurrentCategory()
{
if (treeCategories.SelectedNode != null && treeCategories.SelectedNode != treeCategories.Nodes[0])
{
return GetNodeFullPath(treeCategories.SelectedNode);
}
return "未分类";
}
private void ShowImportResult(int successCount, int errorCount, List<string> errorFiles)
{
SaveData();
RefreshSnippetList();
string message;
MessageBoxIcon icon;
if (errorCount == 0)
{
message = $"成功导入 {successCount} 个文件!";
icon = MessageBoxIcon.Information;
}
else if (successCount == 0)
{
message = $"导入失败!所有 {errorCount} 个文件都未能导入。\n\n失败文件:\n{string.Join("\n", errorFiles)}";
icon = MessageBoxIcon.Error;
}
else
{
message = $"导入完成!\n成功:{successCount} 个文件\n失败:{errorCount} 个文件\n\n失败文件:\n{string.Join("\n", errorFiles)}";
icon = MessageBoxIcon.Warning;
}
MessageBox.Show(message, "导入结果", MessageBoxButtons.OK, icon);
}
// 添加快捷键支持(Ctrl+I 导入)
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.I))
{
ImportFiles();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void TxtCode_TextChanged(object sender, EventArgs e)
{
ApplySyntaxHighlighting();
UpdateLineNumbers();
}
private void TxtCode_VScroll(object sender, EventArgs e)
{
UpdateLineNumbers();
}
private void TxtCode_SelectionChanged(object sender, EventArgs e)
{
UpdateLineNumbers();
}
// 语言选择改变时重新应用语法高亮
private void CmbLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
ApplySyntaxHighlighting();
}
// 应用语法高亮
private void ApplySyntaxHighlighting()
{
if (string.IsNullOrWhiteSpace(txtCode.Text))
return;
string language = cmbLanguage.SelectedItem?.ToString() ?? "其他";
// 保存当前光标位置
int currentPosition = txtCode.SelectionStart;
int currentLength = txtCode.SelectionLength;
// 暂停重绘
txtCode.SuspendLayout();
try
{
// 获取当前文本
string text = txtCode.Text;
// 清除所有格式
txtCode.SelectAll();
txtCode.SelectionColor = normalColor;
txtCode.DeselectAll();
// 应用基本语法高亮
ApplyBasicHighlighting(text, language);
}
catch (Exception ex)
{
// 忽略语法高亮错误
System.Diagnostics.Debug.WriteLine($"语法高亮错误: {ex.Message}");
}
finally
{
// 恢复光标位置
txtCode.Select(currentPosition, currentLength);
// 恢复重绘
txtCode.ResumeLayout();
}
}
private void ApplyBasicHighlighting(string text, string language)
{
// 高亮注释
HighlightPattern(text, @"//.*", commentColor);
HighlightPattern(text, @"/\*.*?\*/", commentColor, RegexOptions.Singleline);
HighlightPattern(text, @"#.*", commentColor);
// 高亮字符串
HighlightPattern(text, @"""[^""\\]*(\\.[^""\\]*)*""", stringColor);
HighlightPattern(text, @"'[^'\\]*(\\.[^'\\]*)*'", stringColor);
HighlightPattern(text, @"`[^`\\]*(\\.[^`\\]*)*`", stringColor);
// 高亮数字
HighlightPattern(text, @"\b\d+(\.\d+)?\b", numberColor);
// 高亮关键字
if (languageKeywords.ContainsKey(language))
{
foreach (string keyword in languageKeywords[language])
{
HighlightPattern(text, $@"\b{keyword}\b", keywordColor);
}
}
// 高亮类型
foreach (string type in typeKeywords)
{
HighlightPattern(text, $@"\b{type}\b", typeColor);
}
}
private void HighlightPattern(string text, string pattern, Color color, RegexOptions options = RegexOptions.None)
{
try
{
var matches = Regex.Matches(text, pattern, options);
foreach (Match match in matches)
{
if (match.Index < text.Length && match.Length > 0)
{
txtCode.Select(match.Index, match.Length);
txtCode.SelectionColor = color;
}
}
}
catch
{
// 忽略正则表达式错误
}
}
// 复制代码到剪贴板
private void BtnCopy_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(txtCode.Text))
{
try
{
// 如果有选中文本,复制选中文本;否则复制全部文本
string textToCopy = txtCode.SelectedText;
if (string.IsNullOrEmpty(textToCopy))
{
textToCopy = txtCode.Text;
}
Clipboard.SetText(textToCopy);
MessageBox.Show("代码已复制到剪贴板!", "复制成功",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"复制失败: {ex.Message}", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("没有可复制的代码", "提示",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
// 保存代码片段
private void BtnSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtTitle.Text))
{
MessageBox.Show("请输入标题", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtTitle.Focus();
return;
}
if (string.IsNullOrWhiteSpace(txtCode.Text))
{
MessageBox.Show("请输入代码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtCode.Focus();
return;
}
// 获取当前选中的分类
string category = "未分类";
if (treeCategories.SelectedNode != null && treeCategories.SelectedNode != treeCategories.Nodes[0])
{
category = GetNodeFullPath(treeCategories.SelectedNode);
}
var snippet = new CodeSnippet
{
Title = txtTitle.Text.Trim(),
Code = txtCode.Text,
Language = cmbLanguage.SelectedItem?.ToString() ?? "其他",
Description = txtDescription.Text.Trim(),
Tags = txtTags.Text.Split(new[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Trim()).ToArray(),
Category = category,
ModifiedTime = DateTime.Now
};
if (currentEditIndex == -1)
{
// 新增
snippet.CreatedTime = DateTime.Now;
codeSnippets.Add(snippet);
}
else
{
// 编辑
snippet.CreatedTime = codeSnippets[currentEditIndex].CreatedTime;
codeSnippets[currentEditIndex] = snippet;
}
SaveData();
RefreshSnippetList();
ClearInputs();
MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// 清空输入框
private void ClearInputs()
{
txtTitle.Clear();
txtCode.Clear();
txtDescription.Clear();
txtTags.Clear();
txtSearch.Clear();
cmbLanguage.SelectedIndex = 0;
currentEditIndex = -1;
btnSave.Text = "保存代码";
btnDelete.Enabled = false;
txtDetail.Clear();
// 更新行号显示
UpdateLineNumbers();
}
// 列表选择改变
private void LstSnippets_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstSnippets.SelectedIndex >= 0)
{
// 获取过滤后的代码片段列表
string selectedCategory = null;
if (treeCategories.SelectedNode != null && treeCategories.SelectedNode != treeCategories.Nodes[0])
{
selectedCategory = GetNodeFullPath(treeCategories.SelectedNode);
}
var filteredSnippets = codeSnippets.Where(snippet =>
selectedCategory == null || snippet.Category == selectedCategory
).ToList();
if (lstSnippets.SelectedIndex < filteredSnippets.Count)
{
var snippet = filteredSnippets[lstSnippets.SelectedIndex];
currentEditIndex = codeSnippets.IndexOf(snippet);
txtTitle.Text = snippet.Title;
txtCode.Text = snippet.Code;
txtDescription.Text = snippet.Description;
txtTags.Text = string.Join(", ", snippet.Tags);
var languageIndex = cmbLanguage.Items.IndexOf(snippet.Language);
if (languageIndex >= 0)
cmbLanguage.SelectedIndex = languageIndex;
else
cmbLanguage.SelectedIndex = cmbLanguage.Items.IndexOf("其他");
btnSave.Text = "更新代码";
btnDelete.Enabled = true;
UpdateSnippetDetail(snippet);
// 应用语法高亮
ApplySyntaxHighlighting();
// 更新行号显示
UpdateLineNumbers();
// 切换到编辑标签页
tabControl1.SelectedTab = tabPageEdit;
}
}
}
// 代码片段类
public class CodeSnippet
{
public string Title { get; set; } = "";
public string Code { get; set; } = "";
public string Language { get; set; } = "C#";
public string Description { get; set; } = "";
public string[] Tags { get; set; } = Array.Empty<string>();
public string Category { get; set; } = "未分类";
public DateTime CreatedTime { get; set; }
public DateTime ModifiedTime { get; set; }
}
// 分类类
public class CodeCategory
{
public string Name { get; set; } = "";
public string FullPath { get; set; } = "";
public List<CodeCategory> Children { get; set; } = new List<CodeCategory>();
}
// 初始化语法高亮
private void InitializeSyntaxHighlighting()
{
cmbLanguage.Items.AddRange(new string[] {
"C#", "Java", "Python", "JavaScript", "HTML", "CSS",
"SQL", "C++", "C", "PHP", "Ruby", "Go", "Rust", "其他"
});
cmbLanguage.SelectedIndex = 0;
}
// 初始化分类
private void InitializeCategories()
{
LoadCategories();
}
// 加载分类数据
private void LoadCategories()
{
try
{
if (File.Exists(categoriesFile))
{
string json = File.ReadAllText(categoriesFile);
var categories = JsonSerializer.Deserialize<List<CodeCategory>>(json);
if (categories != null && categories.Count > 0)
{
treeCategories.Nodes.Clear();
BuildTreeFromCategories(categories);
treeCategories.ExpandAll();
return;
}
}
// 如果文件不存在或为空,创建默认分类
CreateDefaultCategories();
}
catch (Exception ex)
{
MessageBox.Show($"加载分类失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
CreateDefaultCategories();
}
}
// 从分类数据构建树节点
private void BuildTreeFromCategories(List<CodeCategory> categories)
{
foreach (var category in categories)
{
var node = new TreeNode(category.Name)
{
Tag = category.FullPath
};
treeCategories.Nodes.Add(node);
BuildChildNodes(node, category.Children);
}
}
// 递归构建子节点
private void BuildChildNodes(TreeNode parentNode, List<CodeCategory> children)
{
foreach (var child in children)
{
var childNode = new TreeNode(child.Name)
{
Tag = child.FullPath
};
parentNode.Nodes.Add(childNode);
BuildChildNodes(childNode, child.Children);
}
}
// 创建默认分类
private void CreateDefaultCategories()
{
treeCategories.Nodes.Clear();
var rootNode = new TreeNode("所有代码")
{
Tag = "所有代码"
};
treeCategories.Nodes.Add(rootNode);
var defaultCategories = new[] { "C#", "Java", "Python", "JavaScript", "HTML/CSS", "数据库", "算法", "工具类" };
foreach (var category in defaultCategories)
{
var node = new TreeNode(category)
{
Tag = $"所有代码\\{category}"
};
rootNode.Nodes.Add(node);
}
treeCategories.ExpandAll();
SaveCategories(); // 保存默认分类
}
// 保存分类数据
private void SaveCategories()
{
try
{
var categories = BuildCategoriesFromTree();
string json = JsonSerializer.Serialize(categories, new JsonSerializerOptions
{
WriteIndented = true
});
File.WriteAllText(categoriesFile, json, Encoding.UTF8);
}
catch (Exception ex)
{
MessageBox.Show($"保存分类失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// 从树节点构建分类数据
private List<CodeCategory> BuildCategoriesFromTree()
{
var categories = new List<CodeCategory>();
foreach (TreeNode node in treeCategories.Nodes)
{
categories.Add(BuildCategoryFromNode(node, ""));
}
return categories;
}
private CodeCategory BuildCategoryFromNode(TreeNode node, string parentPath)
{
string fullPath = string.IsNullOrEmpty(parentPath) ? node.Text : $"{parentPath}\\{node.Text}";
var category = new CodeCategory
{
Name = node.Text,
FullPath = fullPath
};
foreach (TreeNode childNode in node.Nodes)
{
category.Children.Add(BuildCategoryFromNode(childNode, fullPath));
}
return category;
}
// 添加分类
private void BtnAddCategory_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtNewCategory.Text))
{
MessageBox.Show("请输入分类名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
TreeNode selectedNode = treeCategories.SelectedNode;
TreeNode parentNode = selectedNode ?? treeCategories.Nodes[0]; // 默认添加到根节点或选中节点
string newCategoryName = txtNewCategory.Text.Trim();
var newNode = new TreeNode(newCategoryName);
parentNode.Nodes.Add(newNode);
parentNode.Expand();
treeCategories.SelectedNode = newNode;
txtNewCategory.Clear();
SaveCategories(); // 保存分类
MessageBox.Show($"分类 '{newCategoryName}' 添加成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// 删除分类
private void BtnDeleteCategory_Click(object sender, EventArgs e)
{
TreeNode selectedNode = treeCategories.SelectedNode;
if (selectedNode == null)
{
MessageBox.Show("请选择要删除的分类", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (selectedNode == treeCategories.Nodes[0]) // 根节点
{
MessageBox.Show("不能删除根节点", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// 检查该分类下是否有代码片段
string categoryPath = GetNodeFullPath(selectedNode);
bool hasSnippets = codeSnippets.Any(snippet => snippet.Category == categoryPath);
if (hasSnippets)
{
var result = MessageBox.Show($"分类 '{selectedNode.Text}' 下还有代码片段,删除分类将会把这些代码移到未分类。确定要删除吗?",
"确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
// 将该分类下的代码移到未分类
foreach (var snippet in codeSnippets.Where(s => s.Category == categoryPath))
{
snippet.Category = "未分类";
}
SaveData(); // 保存代码数据
}
else
{
return;
}
}
else
{
var result = MessageBox.Show($"确定要删除分类 '{selectedNode.Text}' 吗?", "确认删除",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result != DialogResult.Yes)
return;
}
selectedNode.Remove();
SaveCategories(); // 保存分类
RefreshSnippetList(); // 刷新代码列表
MessageBox.Show("分类删除成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// 获取节点的完整路径
private string GetNodeFullPath(TreeNode node)
{
if (node.Parent == null)
return node.Text;
return $"{GetNodeFullPath(node.Parent)}\\{node.Text}";
}
// 分类选择变化
private void TreeCategories_AfterSelect(object sender, TreeViewEventArgs e)
{
RefreshSnippetList();
}
// 分类输入框回车键
private void TxtNewCategory_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
BtnAddCategory_Click(sender, e);
e.Handled = true;
}
}
// 窗体关闭事件
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
SaveCategories();
}
// 加载数据
private void LoadData()
{
try
{
if (File.Exists(dataFile))
{
string json = File.ReadAllText(dataFile);
codeSnippets = JsonSerializer.Deserialize<List<CodeSnippet>>(json) ?? new List<CodeSnippet>();
}
else
{
codeSnippets = new List<CodeSnippet>();
}
}
catch (Exception ex)
{
MessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
codeSnippets = new List<CodeSnippet>();
}
}
// 保存数据
private void SaveData()
{
try
{
string json = JsonSerializer.Serialize(codeSnippets, new JsonSerializerOptions
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
File.WriteAllText(dataFile, json, Encoding.UTF8);
}
catch (Exception ex)
{
MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// 刷新代码片段列表
private void RefreshSnippetList()
{
lstSnippets.Items.Clear();
// 根据选中的分类过滤代码片段
string selectedCategory = null;
if (treeCategories.SelectedNode != null && treeCategories.SelectedNode != treeCategories.Nodes[0])
{
selectedCategory = GetNodeFullPath(treeCategories.SelectedNode);
}
var filteredSnippets = codeSnippets.Where(snippet =>
selectedCategory == null || snippet.Category == selectedCategory
).ToList();
foreach (var snippet in filteredSnippets)
{
lstSnippets.Items.Add($"{snippet.Title} [{snippet.Language}] - {snippet.CreatedTime:MM/dd HH:mm}");
}
}
// 更新代码详情显示
private void UpdateSnippetDetail(CodeSnippet snippet)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"标题: {snippet.Title}");
sb.AppendLine($"语言: {snippet.Language}");
sb.AppendLine($"分类: {snippet.Category}");
sb.AppendLine($"创建时间: {snippet.CreatedTime:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine($"修改时间: {snippet.ModifiedTime:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine($"标签: {string.Join(", ", snippet.Tags)}");
sb.AppendLine($"描述: {snippet.Description}");
sb.AppendLine();
sb.AppendLine("代码内容:");
sb.AppendLine(new string('=', 50));
sb.AppendLine(snippet.Code);
txtDetail.Text = sb.ToString();
}
// 删除代码片段
private void BtnDelete_Click(object sender, EventArgs e)
{
if (currentEditIndex >= 0 && currentEditIndex < codeSnippets.Count)
{
var result = MessageBox.Show("确定要删除这个代码片段吗?", "确认删除",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
codeSnippets.RemoveAt(currentEditIndex);
SaveData();
RefreshSnippetList();
ClearInputs();
MessageBox.Show("删除成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
// 新建代码片段
private void BtnNew_Click(object sender, EventArgs e)
{
ClearInputs();
}
// 搜索代码片段
private void BtnSearch_Click(object sender, EventArgs e)
{
string keyword = txtSearch.Text.ToLower().Trim();
if (string.IsNullOrEmpty(keyword))
{
RefreshSnippetList();
return;
}
lstSnippets.Items.Clear();
string selectedCategory = null;
if (treeCategories.SelectedNode != null && treeCategories.SelectedNode != treeCategories.Nodes[0])
{
selectedCategory = GetNodeFullPath(treeCategories.SelectedNode);
}
var filteredSnippets = codeSnippets.Where(snippet =>
(selectedCategory == null || snippet.Category == selectedCategory) &&
(snippet.Title.ToLower().Contains(keyword) ||
snippet.Code.ToLower().Contains(keyword) ||
snippet.Description.ToLower().Contains(keyword) ||
snippet.Tags.Any(tag => tag.ToLower().Contains(keyword)) ||
snippet.Language.ToLower().Contains(keyword))
).ToList();
foreach (var snippet in filteredSnippets)
{
lstSnippets.Items.Add($"{snippet.Title} [{snippet.Language}] - {snippet.CreatedTime:MM/dd HH:mm}");
}
if (filteredSnippets.Count == 0)
{
MessageBox.Show("没有找到匹配的代码片段", "搜索结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
// 导出所有代码
private void BtnExport_Click(object sender, EventArgs e)
{
if (codeSnippets.Count == 0)
{
MessageBox.Show("没有代码片段可导出", "提示",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
using (var saveDialog = new SaveFileDialog())
{
saveDialog.Filter = "文本文件|*.txt|Markdown文件|*.md|所有文件|*.*";
saveDialog.Title = "导出代码库";
saveDialog.FileName = $"代码收藏库_{DateTime.Now:yyyyMMdd_HHmmss}";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
try
{
string extension = Path.GetExtension(saveDialog.FileName).ToLower();
string content = extension == ".md" ? GenerateMarkdownExport() : GenerateTextExport();
File.WriteAllText(saveDialog.FileName, content, Encoding.UTF8);
MessageBox.Show($"导出成功!共导出 {codeSnippets.Count} 个代码片段", "提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"导出失败: {ex.Message}", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
// 生成文本格式导出内容
private string GenerateTextExport()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("代码收藏库导出");
sb.AppendLine($"导出时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine($"代码片段数量: {codeSnippets.Count}");
sb.AppendLine(new string('=', 60));
sb.AppendLine();
foreach (var snippet in codeSnippets)
{
sb.AppendLine($"标题: {snippet.Title}");
sb.AppendLine($"语言: {snippet.Language}");
sb.AppendLine($"分类: {snippet.Category}");
sb.AppendLine($"创建时间: {snippet.CreatedTime:yyyy-MM-dd HH:mm}");
sb.AppendLine($"修改时间: {snippet.ModifiedTime:yyyy-MM-dd HH:mm}");
sb.AppendLine($"标签: {string.Join(", ", snippet.Tags)}");
sb.AppendLine($"描述: {snippet.Description}");
sb.AppendLine("代码:");
sb.AppendLine(snippet.Code);
sb.AppendLine(new string('-', 40));
sb.AppendLine();
}
return sb.ToString();
}
// 生成Markdown格式导出内容
private string GenerateMarkdownExport()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("# 代码收藏库导出");
sb.AppendLine();
sb.AppendLine($"- **导出时间**: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine($"- **代码片段数量**: {codeSnippets.Count}");
sb.AppendLine();
foreach (var snippet in codeSnippets)
{
sb.AppendLine($"## {snippet.Title}");
sb.AppendLine();
sb.AppendLine($"- **语言**: {snippet.Language}");
sb.AppendLine($"- **分类**: {snippet.Category}");
sb.AppendLine($"- **创建时间**: {snippet.CreatedTime:yyyy-MM-dd HH:mm}");
sb.AppendLine($"- **修改时间**: {snippet.ModifiedTime:yyyy-MM-dd HH:mm}");
sb.AppendLine($"- **标签**: {string.Join(", ", snippet.Tags)}");
sb.AppendLine($"- **描述**: {snippet.Description}");
sb.AppendLine();
sb.AppendLine("```" + snippet.Language.ToLower());
sb.AppendLine(snippet.Code);
sb.AppendLine("```");
sb.AppendLine();
sb.AppendLine("---");
sb.AppendLine();
}
return sb.ToString();
}
}
}
Form1.Designer.cs
namespace 代码收藏
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
splitContainer1 = new SplitContainer();
treeCategories = new TreeView();
panel1 = new Panel();
btnDeleteCategory = new Button();
btnAddCategory = new Button();
txtNewCategory = new TextBox();
label1 = new Label();
tabControl1 = new TabControl();
tabPageEdit = new TabPage();
panelCodeContainer = new Panel();
txtCode = new RichTextBox();
panelLineNumbers = new Panel();
panel3 = new Panel();
btnImport = new Button();
btnExport = new Button();
btnSave = new Button();
btnNew = new Button();
btnDelete = new Button();
btnCopy = new Button();
panel2 = new Panel();
cmbLanguage = new ComboBox();
label5 = new Label();
txtTags = new TextBox();
label4 = new Label();
txtDescription = new TextBox();
label3 = new Label();
txtTitle = new TextBox();
label2 = new Label();
tabPageList = new TabPage();
txtDetail = new TextBox();
lstSnippets = new ListBox();
btnSearch = new Button();
txtSearch = new TextBox();
((System.ComponentModel.ISupportInitialize)splitContainer1).BeginInit();
splitContainer1.Panel1.SuspendLayout();
splitContainer1.Panel2.SuspendLayout();
splitContainer1.SuspendLayout();
panel1.SuspendLayout();
tabControl1.SuspendLayout();
tabPageEdit.SuspendLayout();
panelCodeContainer.SuspendLayout();
panel3.SuspendLayout();
panel2.SuspendLayout();
tabPageList.SuspendLayout();
SuspendLayout();
//
// splitContainer1
//
splitContainer1.Dock = DockStyle.Fill;
splitContainer1.Location = new Point(0, 0);
splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
splitContainer1.Panel1.Controls.Add(treeCategories);
splitContainer1.Panel1.Controls.Add(panel1);
splitContainer1.Panel1MinSize = 200;
//
// splitContainer1.Panel2
//
splitContainer1.Panel2.Controls.Add(tabControl1);
splitContainer1.Panel2MinSize = 400;
splitContainer1.Size = new Size(1000, 600);
splitContainer1.SplitterDistance = 250;
splitContainer1.TabIndex = 0;
//
// treeCategories
//
treeCategories.Dock = DockStyle.Fill;
treeCategories.Location = new Point(0, 40);
treeCategories.Name = "treeCategories";
treeCategories.Size = new Size(250, 560);
treeCategories.TabIndex = 1;
//
// panel1
//
panel1.Controls.Add(btnDeleteCategory);
panel1.Controls.Add(btnAddCategory);
panel1.Controls.Add(txtNewCategory);
panel1.Controls.Add(label1);
panel1.Dock = DockStyle.Top;
panel1.Location = new Point(0, 0);
panel1.Name = "panel1";
panel1.Size = new Size(250, 40);
panel1.TabIndex = 0;
//
// btnDeleteCategory
//
btnDeleteCategory.Location = new Point(200, 8);
btnDeleteCategory.Name = "btnDeleteCategory";
btnDeleteCategory.Size = new Size(45, 23);
btnDeleteCategory.TabIndex = 3;
btnDeleteCategory.Text = "删除";
btnDeleteCategory.UseVisualStyleBackColor = true;
//
// btnAddCategory
//
btnAddCategory.Location = new Point(150, 8);
btnAddCategory.Name = "btnAddCategory";
btnAddCategory.Size = new Size(45, 23);
btnAddCategory.TabIndex = 2;
btnAddCategory.Text = "添加";
btnAddCategory.UseVisualStyleBackColor = true;
//
// txtNewCategory
//
txtNewCategory.Location = new Point(40, 8);
txtNewCategory.Name = "txtNewCategory";
txtNewCategory.Size = new Size(105, 23);
txtNewCategory.TabIndex = 1;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(8, 12);
label1.Name = "label1";
label1.Size = new Size(32, 17);
label1.TabIndex = 0;
label1.Text = "分类";
//
// tabControl1
//
tabControl1.Controls.Add(tabPageEdit);
tabControl1.Controls.Add(tabPageList);
tabControl1.Dock = DockStyle.Fill;
tabControl1.Location = new Point(0, 0);
tabControl1.Name = "tabControl1";
tabControl1.SelectedIndex = 0;
tabControl1.Size = new Size(746, 600);
tabControl1.TabIndex = 0;
//
// tabPageEdit
//
tabPageEdit.Controls.Add(panelCodeContainer);
tabPageEdit.Controls.Add(panel3);
tabPageEdit.Controls.Add(panel2);
tabPageEdit.Location = new Point(4, 26);
tabPageEdit.Name = "tabPageEdit";
tabPageEdit.Padding = new Padding(3);
tabPageEdit.Size = new Size(738, 570);
tabPageEdit.TabIndex = 0;
tabPageEdit.Text = "编辑代码";
tabPageEdit.UseVisualStyleBackColor = true;
//
// panelCodeContainer
//
panelCodeContainer.Controls.Add(txtCode);
panelCodeContainer.Controls.Add(panelLineNumbers);
panelCodeContainer.Dock = DockStyle.Fill;
panelCodeContainer.Location = new Point(3, 103);
panelCodeContainer.Name = "panelCodeContainer";
panelCodeContainer.Size = new Size(732, 432);
panelCodeContainer.TabIndex = 4;
//
// txtCode
//
txtCode.Dock = DockStyle.Fill;
txtCode.Font = new Font("Consolas", 10F);
txtCode.Location = new Point(50, 0);
txtCode.Name = "txtCode";
txtCode.Size = new Size(682, 432);
txtCode.TabIndex = 1;
txtCode.Text = "";
//
// panelLineNumbers
//
panelLineNumbers.Dock = DockStyle.Left;
panelLineNumbers.Location = new Point(0, 0);
panelLineNumbers.Name = "panelLineNumbers";
panelLineNumbers.Size = new Size(50, 432);
panelLineNumbers.TabIndex = 0;
//
// panel3
//
panel3.Controls.Add(btnImport);
panel3.Controls.Add(btnExport);
panel3.Controls.Add(btnSave);
panel3.Controls.Add(btnNew);
panel3.Controls.Add(btnDelete);
panel3.Controls.Add(btnCopy);
panel3.Dock = DockStyle.Bottom;
panel3.Location = new Point(3, 535);
panel3.Name = "panel3";
panel3.Size = new Size(732, 32);
panel3.TabIndex = 2;
//
// btnImport
//
btnImport.Location = new Point(413, 4);
btnImport.Name = "btnImport";
btnImport.Size = new Size(75, 25);
btnImport.TabIndex = 5;
btnImport.Text = "导入文件";
btnImport.UseVisualStyleBackColor = true;
//
// btnExport
//
btnExport.Location = new Point(332, 4);
btnExport.Name = "btnExport";
btnExport.Size = new Size(75, 25);
btnExport.TabIndex = 4;
btnExport.Text = "导出";
btnExport.UseVisualStyleBackColor = true;
//
// btnSave
//
btnSave.Location = new Point(8, 4);
btnSave.Name = "btnSave";
btnSave.Size = new Size(75, 25);
btnSave.TabIndex = 0;
btnSave.Text = "保存";
btnSave.UseVisualStyleBackColor = true;
//
// btnNew
//
btnNew.Location = new Point(89, 4);
btnNew.Name = "btnNew";
btnNew.Size = new Size(75, 25);
btnNew.TabIndex = 1;
btnNew.Text = "新建";
btnNew.UseVisualStyleBackColor = true;
//
// btnDelete
//
btnDelete.Enabled = false;
btnDelete.Location = new Point(170, 4);
btnDelete.Name = "btnDelete";
btnDelete.Size = new Size(75, 25);
btnDelete.TabIndex = 2;
btnDelete.Text = "删除";
btnDelete.UseVisualStyleBackColor = true;
//
// btnCopy
//
btnCopy.Location = new Point(251, 4);
btnCopy.Name = "btnCopy";
btnCopy.Size = new Size(75, 25);
btnCopy.TabIndex = 3;
btnCopy.Text = "复制代码";
btnCopy.UseVisualStyleBackColor = true;
//
// panel2
//
panel2.Controls.Add(cmbLanguage);
panel2.Controls.Add(label5);
panel2.Controls.Add(txtTags);
panel2.Controls.Add(label4);
panel2.Controls.Add(txtDescription);
panel2.Controls.Add(label3);
panel2.Controls.Add(txtTitle);
panel2.Controls.Add(label2);
panel2.Dock = DockStyle.Top;
panel2.Location = new Point(3, 3);
panel2.Name = "panel2";
panel2.Size = new Size(732, 100);
panel2.TabIndex = 1;
//
// cmbLanguage
//
cmbLanguage.FormattingEnabled = true;
cmbLanguage.Location = new Point(280, 8);
cmbLanguage.Name = "cmbLanguage";
cmbLanguage.Size = new Size(121, 25);
cmbLanguage.TabIndex = 7;
//
// label5
//
label5.AutoSize = true;
label5.Location = new Point(242, 12);
label5.Name = "label5";
label5.Size = new Size(32, 17);
label5.TabIndex = 6;
label5.Text = "语言";
//
// txtTags
//
txtTags.Location = new Point(280, 40);
txtTags.Name = "txtTags";
txtTags.Size = new Size(200, 23);
txtTags.TabIndex = 5;
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(242, 43);
label4.Name = "label4";
label4.Size = new Size(32, 17);
label4.TabIndex = 4;
label4.Text = "标签";
//
// txtDescription
//
txtDescription.Location = new Point(60, 40);
txtDescription.Name = "txtDescription";
txtDescription.Size = new Size(170, 23);
txtDescription.TabIndex = 3;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(22, 43);
label3.Name = "label3";
label3.Size = new Size(32, 17);
label3.TabIndex = 2;
label3.Text = "描述";
//
// txtTitle
//
txtTitle.Location = new Point(60, 8);
txtTitle.Name = "txtTitle";
txtTitle.Size = new Size(170, 23);
txtTitle.TabIndex = 1;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(22, 12);
label2.Name = "label2";
label2.Size = new Size(32, 17);
label2.TabIndex = 0;
label2.Text = "标题";
//
// tabPageList
//
tabPageList.Controls.Add(txtDetail);
tabPageList.Controls.Add(lstSnippets);
tabPageList.Controls.Add(btnSearch);
tabPageList.Controls.Add(txtSearch);
tabPageList.Location = new Point(4, 26);
tabPageList.Name = "tabPageList";
tabPageList.Padding = new Padding(3);
tabPageList.Size = new Size(738, 570);
tabPageList.TabIndex = 1;
tabPageList.Text = "代码列表";
tabPageList.UseVisualStyleBackColor = true;
//
// txtDetail
//
txtDetail.Location = new Point(8, 240);
txtDetail.Multiline = true;
txtDetail.Name = "txtDetail";
txtDetail.ReadOnly = true;
txtDetail.ScrollBars = ScrollBars.Both;
txtDetail.Size = new Size(722, 322);
txtDetail.TabIndex = 3;
//
// lstSnippets
//
lstSnippets.FormattingEnabled = true;
lstSnippets.ItemHeight = 17;
lstSnippets.Location = new Point(8, 40);
lstSnippets.Name = "lstSnippets";
lstSnippets.Size = new Size(722, 191);
lstSnippets.TabIndex = 2;
//
// btnSearch
//
btnSearch.Location = new Point(214, 8);
btnSearch.Name = "btnSearch";
btnSearch.Size = new Size(75, 23);
btnSearch.TabIndex = 1;
btnSearch.Text = "搜索";
btnSearch.UseVisualStyleBackColor = true;
//
// txtSearch
//
txtSearch.Location = new Point(8, 8);
txtSearch.Name = "txtSearch";
txtSearch.Size = new Size(200, 23);
txtSearch.TabIndex = 0;
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1000, 600);
Controls.Add(splitContainer1);
Name = "Form1";
Text = "代码收藏管理器";
splitContainer1.Panel1.ResumeLayout(false);
splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)splitContainer1).EndInit();
splitContainer1.ResumeLayout(false);
panel1.ResumeLayout(false);
panel1.PerformLayout();
tabControl1.ResumeLayout(false);
tabPageEdit.ResumeLayout(false);
panelCodeContainer.ResumeLayout(false);
panel3.ResumeLayout(false);
panel2.ResumeLayout(false);
panel2.PerformLayout();
tabPageList.ResumeLayout(false);
tabPageList.PerformLayout();
ResumeLayout(false);
}
#endregion
private SplitContainer splitContainer1;
private TreeView treeCategories;
private Panel panel1;
private Button btnDeleteCategory;
private Button btnAddCategory;
private TextBox txtNewCategory;
private Label label1;
private TabControl tabControl1;
private TabPage tabPageEdit;
private Panel panelCodeContainer;
private RichTextBox txtCode;
private Panel panelLineNumbers;
private Panel panel3;
private Button btnImport;
private Button btnExport;
private Button btnSave;
private Button btnNew;
private Button btnDelete;
private Button btnCopy;
private Panel panel2;
private ComboBox cmbLanguage;
private Label label5;
private TextBox txtTags;
private Label label4;
private TextBox txtDescription;
private Label label3;
private TextBox txtTitle;
private Label label2;
private TabPage tabPageList;
private TextBox txtDetail;
private ListBox lstSnippets;
private Button btnSearch;
private TextBox txtSearch;
}
}
Program.cs
using System;
using System.Windows.Forms;
namespace 代码收藏
{
internal static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
显示效果


更多推荐



所有评论(0)