多窗体:新建 / 删除窗体,项目 1 登录示例;标识符支持中文

- 新建窗体:生成与 VS 新建窗体相同的 X.cs 和 X.Designer.cs,沿用工程命名空间;
  删除窗体(启动窗体不能删)
- 标签页按窗体分组,启动窗体排在最前并默认打开
- 运行时点哪个窗口哪个到最前;消息框始终在所有窗口之上
- 示例:项目 1 任务 1 登录与增加用户,两个窗体的 Designer.cs 由设计器引擎生成;
  修正书上未声明的 change 变量、关闭后重复 Show 已释放窗体的问题
- 设计器的正则支持中文控件名、类名、命名空间
- 修正:切换窗体时属性窗口的名称没有刷新
- 测试:多窗体端到端测试;新窗体模板测试

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
xuyueandClaude Opus 5.5 committed 2026-10-22 11:23:37 +08:00
1 parent 02d2f0eabc
commit 8feda289de
19 files changed
+739 -36

No files matched your search

+4 -3
View File
@@ -61,11 +61,12 @@ bun test/load.ts 100 # 压力测试:同时运行 100 个学生程序
- **虚拟实训台**:按教材实训台布局图排列(红外对射、警示灯、LED 屏、照明灯、人体红外、温湿度、光照、烟雾、火焰、ADAM 模块)。每个浏览器会话一台,状态由服务器统一保存:传感器读数由网页上的滑块和开关设定,经服务器推给学生程序;灯、继电器、LED 屏由学生程序控制。
- 新控件:CheckBox、RadioButton(事件顺序与 WinForms 一致),教材控件库的 Lamp、Alarm。
- 示例工程(按书上代码整理):项目 2 任务 1–3、项目 3 任务 1–2。网址带 `?sample=示例编号` 可直接打开指定示例。
- 示例工程(按书上代码整理):项目 1 任务 1、项目 2 任务 1–3、项目 3 任务 1–2。网址带 `?sample=示例编号` 可直接打开指定示例。
- 代码编辑器(Monaco):C# 高亮、编译错误波浪线、点错误跳到对应行、F5 运行 / Shift+F5 停止、草稿自动保存在浏览器本地。
- 窗体设计器(仿 VS):工具箱、拖放与改大小、属性窗口、事件窗口、双击生成事件处理方法;读写 VS 格式的 Designer.cs。
- 窗体设计器(仿 VS,界面中文):工具箱、拖放与改大小、属性窗口、事件窗口、双击生成事件处理方法、撤销 / 重做;读写 VS 格式的 Designer.cs。
- 多窗体:新建、删除窗体;运行时多个窗口可切换前后。
尚未完成:
- 学生代码目前直接在本机进程里运行,**还没有沙箱**,只能在本机开发时使用;部署前要改为在 Docker 容器中运行。
- 多窗体(新建窗体)、设计器的撤销 / 重做、账号和班级、自动评测。
- 导入教材参考工程、账号和班级、自动评测。
+4 -2
View File
@@ -200,7 +200,7 @@ IOT/
| 项目 | 教材内容 | 平台需要支持 | 状态 |
| --- | --- | --- | --- |
| 1 C# 入门基础 | 登录与新增用户(两个窗体)、计算器、继承与多态演示 | 多窗体、Label、TextBox(PasswordChar)、Button、ComboBox、MessageBox、控制台输出 | 控件已有,示例待整理 |
| 1 C# 入门基础 | 登录与新增用户(两个窗体)、计算器、继承与多态演示 | 多窗体、Label、TextBox(PasswordChar)、Button、ComboBox、MessageBox、控制台输出 | 任务 1 已完成,任务 2 示例待整理 |
| 2 环境监测 | LED 屏推送文字;4017 采集温湿度和光照;采集后推送 LED | LED 控件、ledHelper、adam4017Helper、GroupBox、虚拟 COM 口 | 已完成 |
| 3 智慧路灯 | ZigBee 开关路灯;人体红外每 5 秒检测并联动路灯 | Lamp 控件、zigBeeHelper、adam4150Helper、CheckBox、RadioButton、Timer | 已完成 |
| 4 入侵监测 | 红外对射检测;网络摄像机画面与云台;报警灯 | PictureBox、摄像头仿真、Alarm 控件、图片保存 | |
@@ -227,7 +227,7 @@ IOT/
```mermaid
flowchart TB
P0["阶段 0 · 技术验证(已完成 2026-10-22)<br/>教材项目 2 任务 1 原样运行;实测编译、延迟、内存"]
P1["阶段 1 · MVP(进行中,约 3 个月)<br/>虚拟实训台 ✔、项目 2–3 示例 ✔、代码编辑器 ✔、窗体设计器 ✔<br/>多窗体、导入教材参考工程"]
P1["阶段 1 · MVP(进行中,约 3 个月)<br/>虚拟实训台 ✔、项目 1–3 示例 ✔、代码编辑器 ✔、窗体设计器 ✔、多窗体 ✔<br/>导入教材参考工程"]
P2["阶段 2 · 教学闭环(约 2 个月)<br/>班级码登录、提交作业、自动评测、老师看板、成绩导出;一个班试用"]
P3["阶段 3 · 扩展(下学期)<br/>教材项目 4–8:摄像头、线程、SQLite 模拟数据库、图表、虚拟时钟"]
P4["阶段 4 · 进阶(之后)<br/>校园街景场景、故障注入题库、导出 VS 工程"]
@@ -256,6 +256,8 @@ flowchart TB
- 2026-10-22:虚拟实训台(服务器统一保存状态,网页调节环境);CheckBox、RadioButton、Lamp、Alarm;教材项目 2、3 共 5 个任务的示例全部跑通。
- 2026-10-22:代码编辑器换成 Monaco:C# 语法高亮;编译错误以波浪线标在代码里,点错误信息跳到对应行;F5 运行、Shift+F5 停止(在整个页面生效,并阻止浏览器 F5 刷新);改过的代码自动保存在浏览器本地,可一键恢复原始代码。前端打包后 JS + CSS 压缩约 1.2 MB。
- 2026-10-22:窗体设计器:工具箱拖放或双击添加控件,选中、拖动、改大小、拖进拖出分组框,Delete 删除、方向键微调;属性窗口和事件窗口;双击控件或事件生成事件处理方法并跳到代码;Timer 等组件显示在组件栏。Designer.cs 在浏览器端直接解析和生成:未改动的语句保留原文,教材 25 个参考窗体和全部示例读入再写出逐字节不变;布局语句(SuspendLayout / ResumeLayout / PerformLayout)的增删规则与 VS 一致。
- 2026-10-22:设计器撤销 / 重做(撤销"生成事件处理方法"时连同插入的方法一起撤掉,不覆盖学生已写的代码);工具箱、属性、事件窗口全部显示中文,英文名放在悬停提示里;支持中文的控件名和类名。
- 2026-10-22:多窗体:新建窗体(与 VS 新建窗体相同的两个文件,沿用工程命名空间)、删除窗体(启动窗体不能删);标签页按窗体分组;运行时点哪个窗口哪个到最前。新增示例:项目 1 任务 1 登录与增加用户(两个窗体的 Designer.cs 由设计器引擎生成)。
## 技术风险与待确认事项
+143
View File
@@ -0,0 +1,143 @@
namespace 登录
{
partial class AddUser
{
/// <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()
{
this.LblUsername = new System.Windows.Forms.Label();
this.txtNewUser1 = new System.Windows.Forms.TextBox();
this.LblPwd = new System.Windows.Forms.Label();
this.txtPass1 = new System.Windows.Forms.TextBox();
this.LblCheckPwd = new System.Windows.Forms.Label();
this.txtPass2 = new System.Windows.Forms.TextBox();
this.btnOk = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// LblUsername
//
this.LblUsername.AutoSize = true;
this.LblUsername.Location = new System.Drawing.Point(25, 27);
this.LblUsername.Name = "LblUsername";
this.LblUsername.Size = new System.Drawing.Size(41, 12);
this.LblUsername.TabIndex = 0;
this.LblUsername.Text = "用户名";
//
// txtNewUser1
//
this.txtNewUser1.Location = new System.Drawing.Point(90, 24);
this.txtNewUser1.Name = "txtNewUser1";
this.txtNewUser1.Size = new System.Drawing.Size(110, 21);
this.txtNewUser1.TabIndex = 1;
//
// LblPwd
//
this.LblPwd.AutoSize = true;
this.LblPwd.Location = new System.Drawing.Point(25, 57);
this.LblPwd.Name = "LblPwd";
this.LblPwd.Size = new System.Drawing.Size(29, 12);
this.LblPwd.TabIndex = 2;
this.LblPwd.Text = "密码";
//
// txtPass1
//
this.txtPass1.Location = new System.Drawing.Point(90, 54);
this.txtPass1.Name = "txtPass1";
this.txtPass1.PasswordChar = '*';
this.txtPass1.Size = new System.Drawing.Size(110, 21);
this.txtPass1.TabIndex = 3;
//
// LblCheckPwd
//
this.LblCheckPwd.AutoSize = true;
this.LblCheckPwd.Location = new System.Drawing.Point(25, 87);
this.LblCheckPwd.Name = "LblCheckPwd";
this.LblCheckPwd.Size = new System.Drawing.Size(53, 12);
this.LblCheckPwd.TabIndex = 4;
this.LblCheckPwd.Text = "确认密码";
//
// txtPass2
//
this.txtPass2.Location = new System.Drawing.Point(90, 84);
this.txtPass2.Name = "txtPass2";
this.txtPass2.PasswordChar = '*';
this.txtPass2.Size = new System.Drawing.Size(110, 21);
this.txtPass2.TabIndex = 5;
//
// btnOk
//
this.btnOk.Location = new System.Drawing.Point(35, 120);
this.btnOk.Name = "btnOk";
this.btnOk.Size = new System.Drawing.Size(75, 23);
this.btnOk.TabIndex = 6;
this.btnOk.Text = "确定";
this.btnOk.UseVisualStyleBackColor = true;
this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(125, 120);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 7;
this.btnCancel.Text = "取消";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// AddUser
//
this.AcceptButton = this.btnOk;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(220, 160);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOk);
this.Controls.Add(this.txtPass2);
this.Controls.Add(this.LblCheckPwd);
this.Controls.Add(this.txtPass1);
this.Controls.Add(this.LblPwd);
this.Controls.Add(this.txtNewUser1);
this.Controls.Add(this.LblUsername);
this.Name = "AddUser";
this.Text = "增加用户";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label LblUsername;
private System.Windows.Forms.TextBox txtNewUser1;
private System.Windows.Forms.Label LblPwd;
private System.Windows.Forms.TextBox txtPass1;
private System.Windows.Forms.Label LblCheckPwd;
private System.Windows.Forms.TextBox txtPass2;
private System.Windows.Forms.Button btnOk;
private System.Windows.Forms.Button btnCancel;
}
}
+48
View File
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 登录
{
public partial class AddUser : Form
{
public AddUser()
{
InitializeComponent();
}
private void btnOk_Click(object sender, EventArgs e)
{
if (PublicData.intNum < 4)//确保还有足够的存储空间
{
if (txtPass1.Text.Equals(txtPass2.Text) && txtPass2.Text != "")//确保两次密码相同且非空
{
//存储新增用户
PublicData.SysUserName[PublicData.intNum] = txtNewUser1.Text;
PublicData.SysPwd[PublicData.intNum] = txtPass1.Text;
PublicData.intNum++;//增加实际存储数量
this.Close();//关闭当前窗体
}
else
{
MessageBox.Show("用户名或密码错误,请重新输入", "新增用户");
}
}
else
{
MessageBox.Show("用户名已满不能增加", "新增用户");
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
+133
View File
@@ -0,0 +1,133 @@
namespace 登录
{
partial class Login
{
/// <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()
{
this.LblUsername = new System.Windows.Forms.Label();
this.txtUserName = new System.Windows.Forms.TextBox();
this.LblPwd = new System.Windows.Forms.Label();
this.txtPassword = new System.Windows.Forms.TextBox();
this.btnOk = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// LblUsername
//
this.LblUsername.AutoSize = true;
this.LblUsername.Location = new System.Drawing.Point(30, 30);
this.LblUsername.Name = "LblUsername";
this.LblUsername.Size = new System.Drawing.Size(53, 12);
this.LblUsername.TabIndex = 0;
this.LblUsername.Text = "用户名称";
//
// txtUserName
//
this.txtUserName.Location = new System.Drawing.Point(100, 27);
this.txtUserName.Name = "txtUserName";
this.txtUserName.Size = new System.Drawing.Size(160, 21);
this.txtUserName.TabIndex = 1;
//
// LblPwd
//
this.LblPwd.AutoSize = true;
this.LblPwd.Location = new System.Drawing.Point(30, 66);
this.LblPwd.Name = "LblPwd";
this.LblPwd.Size = new System.Drawing.Size(29, 12);
this.LblPwd.TabIndex = 2;
this.LblPwd.Text = "密码";
//
// txtPassword
//
this.txtPassword.Location = new System.Drawing.Point(100, 63);
this.txtPassword.Name = "txtPassword";
this.txtPassword.PasswordChar = '*';
this.txtPassword.Size = new System.Drawing.Size(160, 21);
this.txtPassword.TabIndex = 3;
//
// btnOk
//
this.btnOk.Location = new System.Drawing.Point(30, 105);
this.btnOk.Name = "btnOk";
this.btnOk.Size = new System.Drawing.Size(75, 23);
this.btnOk.TabIndex = 4;
this.btnOk.Text = "登录";
this.btnOk.UseVisualStyleBackColor = true;
this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(115, 105);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 5;
this.btnCancel.Text = "取消";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(200, 105);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(75, 23);
this.btnAdd.TabIndex = 6;
this.btnAdd.Text = "增加用户";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// Login
//
this.AcceptButton = this.btnOk;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(300, 150);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOk);
this.Controls.Add(this.txtPassword);
this.Controls.Add(this.LblPwd);
this.Controls.Add(this.txtUserName);
this.Controls.Add(this.LblUsername);
this.Name = "Login";
this.Text = "登录";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label LblUsername;
private System.Windows.Forms.TextBox txtUserName;
private System.Windows.Forms.Label LblPwd;
private System.Windows.Forms.TextBox txtPassword;
private System.Windows.Forms.Button btnOk;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnAdd;
}
}
+57
View File
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 登录
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
public bool IsLogin = false;//定义登录标识
private void btnOk_Click(object sender, EventArgs e)
{
for (int i = 0; i < PublicData.SysUserName.Length; i++)
{
string usr = PublicData.SysUserName[i];
string pwd = PublicData.SysPwd[i];
if (txtUserName.Text == usr && txtPassword.Text == pwd && txtUserName.Text != "")//遍历用户名密码是否存在
{
IsLogin = true;//变更登录标识
MessageBox.Show("登录成功,欢迎进入!", "登录");
PublicData.intUser = i;//存储当前用户在数组中的索引
break;//结束循环
}
else
IsLogin = false;
}
if (IsLogin == false)
{
MessageBox.Show("无效的密码或用户名,请重试", "登录");
txtPassword.Focus();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
IsLogin = false;
this.Close();//关闭当前窗体
}
private void btnAdd_Click(object sender, EventArgs e)
{
AddUser addfrm = new AddUser();//实例化添加用户窗体
addfrm.Show();//显示增加用户窗体
}
}
}
+22
View File
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 登录
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
}
}
+16
View File
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 登录
{
public class PublicData
{
public static string[] SysUserName = new string[4];//存储系统用户名
public static string[] SysPwd = new string[4];//存储系统用户密码
public static int intNum { get; set; }//当前数据存储的用户数量
public static int intUser { get; set; }//记录当前用户索引号
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"title": "项目1 任务1 C#引入(登录与增加用户)",
"source": "教材书 p2–7,按书上代码整理。修正:删去未声明的变量 change;增加用户窗体关闭后会被释放,改为每次点击时新建"
}
+27
View File
@@ -237,3 +237,30 @@ test('项目3 任务2:勾选人体开关后,有人经过时 5 秒内路灯
const on = await runner.next('device', (m) => m.device === 'zigbee', 7000)
expect(on.data).toEqual([1, 1])
}, 30000)
test('项目1 任务1:多窗体——打开增加用户窗体、添加用户、关闭后登录成功,可以再次打开', async () => {
const { runner, form: login, id } = await startSample('p1-t1-登录')
expect(login.props.Text).toBe('登录')
runner.send({ type: 'action', id: id('btnAdd'), action: 'click' })
const { form: addUser } = await runner.waitFor('formShown', (m) => m.form.props.Text === '增加用户')
const addId = (name: string) => findByName(addUser, name).id
runner.send({ type: 'action', id: addId('txtNewUser1'), action: 'text', value: 'admin' })
runner.send({ type: 'action', id: addId('txtPass1'), action: 'text', value: '123' })
runner.send({ type: 'action', id: addId('txtPass2'), action: 'text', value: '123' })
runner.send({ type: 'action', id: addId('btnOk'), action: 'click' })
await runner.waitFor('formClosed', (m) => m.formId === addUser.id)
runner.send({ type: 'action', id: id('txtUserName'), action: 'text', value: 'admin' })
runner.send({ type: 'action', id: id('txtPassword'), action: 'text', value: '123' })
runner.send({ type: 'action', id: id('btnOk'), action: 'click' })
const box = await runner.waitFor('messageBox')
expect(box.text).toBe('登录成功,欢迎进入!')
runner.send({ type: 'reply', requestId: box.requestId, result: 'OK' })
// 再次打开增加用户窗体:每次新建实例,不会因为上一个已释放而出错
runner.send({ type: 'action', id: id('btnAdd'), action: 'click' })
const second = await runner.next('formShown', (m) => m.form.props.Text === '增加用户')
expect(second.form.id).not.toBe(addUser.id)
expect(runner.messages.some((m) => m.type === 'exception')).toBe(false)
}, 30000)
+113 -12
View File
@@ -1,10 +1,11 @@
<script setup lang="ts">
// 主页面:选择示例工程 → 编辑代码 → 运行 → 在网页里操作学生的窗体和虚拟实训台。
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import { NButton, NConfigProvider, NPopconfirm, NSelect, NTab, NTabs, NTag, zhCN } from 'naive-ui'
import { NButton, NConfigProvider, NInput, NPopconfirm, NPopover, NSelect, NTab, NTabs, NTag, zhCN } from 'naive-ui'
import type { SourceFile } from '@iot/shared'
import FormDesigner from './designer/FormDesigner.vue'
import { createDesignerHistory } from './designer/history'
import { formNameTaken, newFormFiles, nextFormName, projectNamespace, startupForm } from './designer/templates'
import CodeEditor from './editor/CodeEditor.vue'
import { clearDraft, loadDraft, saveDraft } from './editor/drafts'
import { createRunSession } from './run/session'
@@ -23,15 +24,26 @@ const activeTab = ref<string>()
const DESIGN = '设计:'
/** 每个 X.Designer.cs 对应一个设计器标签页,和它的代码文件 X.cs */
const forms = computed(() =>
files.value
const forms = computed(() => {
const startup = startupForm(files.value)
return files.value
.filter((f) => f.path.endsWith('.Designer.cs'))
.map((f) => ({ tab: DESIGN + f.path, designer: f.path, code: f.path.replace(/\.Designer\.cs$/, '.cs') })),
)
const tabs = computed(() => [
...forms.value.map((f) => ({ name: f.tab, label: `${f.code} [设计]` })),
...files.value.map((f) => ({ name: f.path, label: f.path })),
])
.map((f) => ({ tab: DESIGN + f.path, designer: f.path, code: f.path.replace(/\.Designer\.cs$/, '.cs') }))
// 启动窗体排在最前
.sort((a, b) => Number(b.code === `${startup}.cs`) - Number(a.code === `${startup}.cs`))
})
/** 标签页按窗体分组:每个窗体依次是 [设计]、代码、Designer.cs;其他文件(Program.cs 等)放最后 */
const tabs = computed(() => {
const grouped = new Set(forms.value.flatMap((f) => [f.code, f.designer]))
return [
...forms.value.flatMap((f) => [
{ name: f.tab, label: `${f.code} [设计]` },
{ name: f.code, label: f.code },
{ name: f.designer, label: f.designer },
]),
...files.value.filter((f) => !grouped.has(f.path)).map((f) => ({ name: f.path, label: f.path })),
]
})
const activeForm = computed(() => forms.value.find((f) => f.tab === activeTab.value))
/** 代码编辑器显示的文件:设计器打开时保持上一次的代码文件 */
const activeFile = computed(() => (activeForm.value ? undefined : activeTab.value))
@@ -91,11 +103,58 @@ function updateFile(path: string, content: string) {
const file = files.value.find((f) => f.path === path)
if (!file || file.content === content) return
file.content = content
filesChanged()
}
function filesChanged() {
modified.value = true
clearTimeout(saveTimer)
saveTimer = setTimeout(() => sampleId.value && saveDraft(sampleId.value, files.value), 500)
}
// ---------- 新建、删除窗体 ----------
const newFormOpen = ref(false)
const newFormName = ref('')
const newFormError = computed(() => {
const name = newFormName.value.trim()
if (!name) return '请输入窗体名'
if (!/^[\p{L}_][\p{L}\p{N}_]*$/u.test(name)) return '只能用字母、汉字、数字、下划线,且不能以数字开头'
if (formNameTaken(files.value, name)) return `已经有名为“${name}”的窗体或类`
return null
})
function openNewForm(show: boolean) {
newFormOpen.value = show
if (show) newFormName.value = nextFormName(files.value)
}
/** 新建窗体:生成 X.cs 和 X.Designer.cs,打开它的设计器 */
function createForm() {
if (newFormError.value) return
const created = newFormFiles(projectNamespace(files.value), newFormName.value.trim())
files.value.push(...created)
filesChanged()
newFormOpen.value = false
activeTab.value = DESIGN + created[1].path
}
/** 当前设计器里的窗体能否删除:启动窗体(Program.cs 里 Application.Run 的那个)不能删 */
const deletableForm = computed(() => {
const form = activeForm.value
if (!form) return undefined
const className = /partial\s+class\s+([\p{L}\p{N}_]+)/u.exec(fileText(form.designer))?.[1]
return className && className !== startupForm(files.value) ? form : undefined
})
function deleteForm() {
const form = deletableForm.value
if (!form) return
files.value = files.value.filter((f) => f.path !== form.designer && f.path !== form.code)
designerHistory.clear(form.designer)
filesChanged()
activeTab.value = forms.value[0]?.tab ?? files.value[0]?.path
}
/** 设计器改动了 Designer.cs(以及插入事件处理方法时的代码文件) */
function onDesignerUpdate(designerText: string, codeText?: string) {
const form = activeForm.value
@@ -166,9 +225,28 @@ function run() {
<main class="workspace" :class="{ designing: activeForm }">
<section class="editor">
<NTabs v-model:value="activeTab" type="card" size="small">
<NTab v-for="tab in tabs" :key="tab.name" :name="tab.name">{{ tab.label }}</NTab>
</NTabs>
<div class="tab-row">
<NTabs v-model:value="activeTab" type="card" size="small" class="file-tabs">
<NTab v-for="tab in tabs" :key="tab.name" :name="tab.name">{{ tab.label }}</NTab>
</NTabs>
<NPopover trigger="click" placement="bottom-end" :show="newFormOpen" @update:show="openNewForm">
<template #trigger>
<NButton size="small" quaternary>+ 新建窗体</NButton>
</template>
<div class="new-form">
<div>窗体名(也是类名和文件名)</div>
<NInput v-model:value="newFormName" size="small" @keydown.enter="createForm" />
<div v-if="newFormError" class="new-form-error">{{ newFormError }}</div>
<NButton size="small" type="primary" :disabled="!!newFormError" @click="createForm">创建</NButton>
</div>
</NPopover>
<NPopconfirm v-if="deletableForm" positive-text="删除" negative-text="取消" @positive-click="deleteForm">
<template #trigger>
<NButton size="small" quaternary>删除窗体</NButton>
</template>
将删除 {{ deletableForm.code }} 和 {{ deletableForm.designer }},代码里用到这个窗体的地方需要自己修改。确定删除吗?
</NPopconfirm>
</div>
<FormDesigner
v-if="activeForm"
class="code"
@@ -289,6 +367,29 @@ body {
min-height: 0;
}
.tab-row {
display: flex;
align-items: flex-start;
gap: 4px;
}
.file-tabs {
flex: 1;
min-width: 0;
}
.new-form {
display: flex;
flex-direction: column;
gap: 6px;
width: 220px;
font-size: 12px;
}
.new-form-error {
color: #dc2626;
}
.run-area {
display: flex;
flex-direction: column;
+2 -1
View File
@@ -44,7 +44,8 @@ function reset(prop: PropDef) {
// ---------- 名称 ----------
const nameDraft = ref('')
const nameError = ref<string | null>(null)
watch(() => props.selected, () => {
// 切换选中的控件或切换到另一个窗体时刷新
watch([() => props.selected, () => props.doc.formName], () => {
nameDraft.value = props.selected || props.doc.formName
nameError.value = null
}, { immediate: true })
+1 -1
View File
@@ -39,7 +39,7 @@ function lineOf(text: string, index: number) {
/** 找到 class className 的类体结束 "}" 的位置(跳过字符串、字符和注释) */
export function classClosingBrace(code: string, className: string): number {
const decl = new RegExp(`\\bclass\\s+${className}\\b`).exec(code)
const decl = new RegExp(`(?<![\\p{L}\\p{N}_])class\\s+${className}(?![\\p{L}\\p{N}_])`, 'u').exec(code)
if (!decl) return -1
let i = code.indexOf('{', decl.index)
if (i < 0) return -1
+10 -10
View File
@@ -123,17 +123,17 @@ function skipVerbatim(text: string, i: number) {
// ---------- 解析 ----------
const CREATE = /^this\.(\w+) = new ([\w.]+)\(([^()]*)\);$/
const LAYOUT = /^this\.(?:(\w+)\.)?(SuspendLayout|ResumeLayout|PerformLayout)\((?:false)?\);$/
const INIT = /^\(\(System\.ComponentModel\.ISupportInitialize\)\(this\.(\w+)\)\)\.(BeginInit|EndInit)\(\);$/
const EVENT = /^this\.(?:(\w+)\.)?(\w+) \+= new ([\w.]+)\(this\.(\w+)\);$/
const ADD = /^this\.(?:(\w+)\.)?Controls\.Add\(this\.(\w+)\);$/
const ITEMS = /^this\.(\w+)\.Items\.AddRange\(new object\[\] \{([\s\S]*)\}\);$/
const PROP = /^this\.([\w.]+) = ([\s\S]+);$/
const CREATE = /^this\.([\p{L}\p{N}_]+) = new ([\p{L}\p{N}_.]+)\(([^()]*)\);$/u
const LAYOUT = /^this\.(?:([\p{L}\p{N}_]+)\.)?(SuspendLayout|ResumeLayout|PerformLayout)\((?:false)?\);$/u
const INIT = /^\(\(System\.ComponentModel\.ISupportInitialize\)\(this\.([\p{L}\p{N}_]+)\)\)\.(BeginInit|EndInit)\(\);$/u
const EVENT = /^this\.(?:([\p{L}\p{N}_]+)\.)?([\p{L}\p{N}_]+) \+= new ([\p{L}\p{N}_.]+)\(this\.([\p{L}\p{N}_]+)\);$/u
const ADD = /^this\.(?:([\p{L}\p{N}_]+)\.)?Controls\.Add\(this\.([\p{L}\p{N}_]+)\);$/u
const ITEMS = /^this\.([\p{L}\p{N}_]+)\.Items\.AddRange\(new object\[\] \{([\s\S]*)\}\);$/u
const PROP = /^this\.([\p{L}\p{N}_.]+) = ([\s\S]+);$/u
/** 一个 Designer.cs 文件里窗体类的名字:partial class 后面的标识符 */
function findFormName(text: string) {
const match = /partial\s+class\s+(\w+)/.exec(text)
const match = /partial\s+class\s+([\p{L}\p{N}_]+)/u.exec(text)
if (!match) throw new DesignerParseError('找不到 partial class 声明')
return match[1]
}
@@ -157,7 +157,7 @@ export function parseDesigner(text: string): DesignerDocument {
// 第一遍:找出所有创建的控件。只有声明了字段的才算控件——
// 窗体属性也可能写成 this.ClientSize = new System.Drawing.Size(...),形式和创建控件一样
const fields = new Set([...text.matchAll(/^\s*private\s+[\w.]+\s+(\w+)\s*;/gm)].map((m) => m[1]))
const fields = new Set([...text.matchAll(/^\s*private\s+[\p{L}\p{N}_.]+\s+([\p{L}\p{N}_]+)\s*;/gmu)].map((m) => m[1]))
const controls = new Set<string>()
for (const piece of pieces) {
const m = piece.kind === 'stmt' ? CREATE.exec(piece.text) : null
@@ -173,7 +173,7 @@ export function parseDesigner(text: string): DesignerDocument {
headerLines.push(piece.text)
// VS 的块头是三行注释:"// "、"// 名字"、"// "
if (headerLines.length === 3) {
const name = /^\/\/ (\w+)$/.exec(headerLines[1])?.[1]
const name = /^\/\/ ([\p{L}\p{N}_]+)$/u.exec(headerLines[1])?.[1]
if (!name || headerLines[0].trim() !== '//' || headerLines[2].trim() !== '//') {
throw new DesignerParseError(`无法识别的注释:${headerLines.join(' ')}`)
}
+4 -4
View File
@@ -236,7 +236,7 @@ export function renameControl(doc: DesignerDocument, from: string, to: string):
case 'layout':
return s.target === from ? { ...s, target: to, text: undefined } : s
case 'raw':
return s.text.includes(`this.${from}`) ? { kind: 'raw', text: s.text.replace(new RegExp(`\\bthis\\.${from}\\b`, 'g'), `this.${to}`) } : s
return s.text.includes(`this.${from}`) ? { kind: 'raw', text: s.text.replace(new RegExp(`(?<![\\p{L}\\p{N}_])this\\.${from}(?![\\p{L}\\p{N}_])`, 'gu'), `this.${to}`) } : s
}
}
next.prologue = next.prologue.map(fix)
@@ -245,7 +245,7 @@ export function renameControl(doc: DesignerDocument, from: string, to: string):
if (block.name === from) block.name = to
block.stmts = block.stmts.map(fix)
}
next.tail = next.tail.replace(new RegExp(`(private [\\w.]+ )${from};`), `$1${to};`)
next.tail = next.tail.replace(new RegExp(`(private [\\p{L}\\p{N}_.]+ )${from};`, 'u'), `$1${to};`)
return next
}
@@ -336,7 +336,7 @@ function ensureLayout(doc: DesignerDocument, target: string, op: 'SuspendLayout'
// ---------- 字段声明 ----------
const FIELD = /^([ \t]*)private ([\w.]+) (\w+);[ \t]*$/gm
const FIELD = /^([ \t]*)private ([\p{L}\p{N}_.]+) ([\p{L}\p{N}_]+);[ \t]*$/gmu
function addField(tail: string, type: string, name: string, eol: string) {
const fields = [...tail.matchAll(FIELD)]
@@ -354,7 +354,7 @@ function addField(tail: string, type: string, name: string, eol: string) {
}
function removeField(tail: string, name: string) {
return tail.replace(new RegExp(`^[ \\t]*private [\\w.]+ ${name};[ \\t]*\\r?\\n`, 'm'), '')
return tail.replace(new RegExp(`^[ \\t]*private [\\p{L}\\p{N}_.]+ ${name};[ \\t]*\\r?\\n`, 'mu'), '')
}
/** 窗体或控件的显示名:窗体用类名 */
+29
View File
@@ -0,0 +1,29 @@
/// <reference types="bun" />
import { expect, test } from 'bun:test'
import { generateDesigner, parseDesigner } from './document'
import { addControl } from './edit'
import { controlDef } from './catalog'
import { formNameTaken, newFormFiles, nextFormName, projectNamespace, startupForm } from './templates'
const files = [
{ path: 'Program.cs', content: 'namespace 登录\n{\n static class Program\n {\n static void Main()\n {\n Application.Run(new Login());\n }\n }\n}\n' },
{ path: 'Login.cs', content: 'namespace 登录\n{\n public partial class Login : Form\n {\n }\n}\n' },
]
test('新窗体沿用工程的命名空间,名字不与已有窗体重复', () => {
expect(projectNamespace(files)).toBe('登录')
expect(nextFormName(files)).toBe('Form2')
expect(formNameTaken(files, 'Login')).toBe(true)
expect(startupForm(files)).toBe('Login')
})
test('新窗体的 Designer.cs 能被设计器打开,添加控件后格式正确', () => {
const [, designer] = newFormFiles('登录', 'AddUser')
const doc = parseDesigner(designer.content)
expect(generateDesigner(doc)).toBe(designer.content)
expect(doc.formName).toBe('AddUser')
const text = generateDesigner(addControl(doc, controlDef('System.Windows.Forms.Button'), '', { x: 10, y: 10 }).doc)
expect(text).toContain(' this.button1 = new System.Windows.Forms.Button();\n this.SuspendLayout();')
expect(text).toContain(' this.Controls.Add(this.button1);\n this.Name = "AddUser";')
expect(text).toContain(' #endregion\n\n private System.Windows.Forms.Button button1;\n }')
})
+106
View File
@@ -0,0 +1,106 @@
// 新建窗体:生成与 VS(中文版、.NET Framework 4.5)新建窗体并保存一次后相同的两个文件。
import type { SourceFile } from '@iot/shared'
/** 工程的命名空间:取 Program.cs(没有就取任意 .cs)里的 namespace */
export function projectNamespace(files: SourceFile[]): string {
const ordered = [...files].sort((a, b) => Number(b.path === 'Program.cs') - Number(a.path === 'Program.cs'))
for (const file of ordered) {
const m = /^\s*namespace\s+([\p{L}\p{N}_.]+)/mu.exec(file.content)
if (m) return m[1]
}
return 'WindowsFormsApplication1'
}
/** 下一个可用的窗体名:Form2、Form3…… */
export function nextFormName(files: SourceFile[]): string {
for (let n = 2; ; n++) if (!formNameTaken(files, `Form${n}`)) return `Form${n}`
}
/** 窗体名是否已被使用(同名文件或同名类) */
export function formNameTaken(files: SourceFile[], name: string): boolean {
return files.some((f) => f.path === `${name}.cs` || f.path === `${name}.Designer.cs` || new RegExp(`(?<![\\p{L}\\p{N}_])class\\s+${name}(?![\\p{L}\\p{N}_])`, 'u').test(f.content))
}
/** Program.cs 里 Application.Run(new X()) 启动的窗体类名 */
export function startupForm(files: SourceFile[]): string | undefined {
const program = files.find((f) => f.path === 'Program.cs')
return program && /Application\.Run\(\s*new\s+([\p{L}\p{N}_]+)\s*\(/u.exec(program.content)?.[1]
}
/** VS 的属性块头:三行注释,第一、三行是 "// "(末尾带空格) */
function blockHeader(name: string) {
return [' // ', ` // ${name}`, ' // '].join('\n')
}
export function newFormFiles(namespace: string, name: string): SourceFile[] {
const code = `using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ${namespace}
{
public partial class ${name} : Form
{
public ${name}()
{
InitializeComponent();
}
}
}
`
const designer = `namespace ${namespace}
{
partial class ${name}
{
/// <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()
{
this.SuspendLayout();
${blockHeader(name)}
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Name = "${name}";
this.Text = "${name}";
this.ResumeLayout(false);
}
#endregion
}
}
`
return [
{ path: `${name}.cs`, content: code },
{ path: `${name}.Designer.cs`, content: designer },
]
}
+13 -1
View File
@@ -1,3 +1,8 @@
<script lang="ts">
let topZ = 1
const nextZ = () => ++topZ
</script>
<script setup lang="ts">
// 一个 WinForms 窗体:标题栏 + 客户区。窗体可以拖动标题栏移动。
import { computed, ref } from 'vue'
@@ -19,6 +24,12 @@ const childrenTopLast = computed(() => [...props.form.children].reverse())
const clientSize = computed(() => (p.value.ClientSize as SizeValue | undefined) ?? { width: 300, height: 300 })
const position = ref({ x: 24 + props.offset * 32, y: 24 + props.offset * 32 })
// 点哪个窗口,哪个窗口到最前面(所有窗体共用一个递增的层级)
const zIndex = ref(nextZ())
function activate() {
zIndex.value = nextZ()
}
let dragStart: { x: number; y: number; px: number; py: number } | undefined
function startDrag(event: PointerEvent) {
@@ -41,7 +52,8 @@ function close() {
v-show="p.Visible !== false"
class="wf-window"
:class="{ 'wf-window-modal': modal }"
:style="{ left: `${position.x}px`, top: `${position.y}px` }"
:style="{ left: `${position.x}px`, top: `${position.y}px`, zIndex: modal ? undefined : zIndex }"
@pointerdown.capture="activate"
>
<div v-if="!borderless" class="wf-titlebar" @pointerdown="startDrag" @pointermove="drag" @pointerup="dragStart = undefined">
<span class="wf-title">{{ displayText(p.Text) }}</span>
+3 -2
View File
@@ -12,7 +12,7 @@
}
.wf-window-modal {
z-index: 10;
z-index: 100000;
}
.wf-titlebar {
@@ -244,7 +244,8 @@
.wf-modal-backdrop {
position: absolute;
inset: 0;
z-index: 20;
/* 在所有窗体(包括模态窗体)之上 */
z-index: 200000;
display: flex;
align-items: center;
justify-content: center;