多窗体:新建 / 删除窗体,项目 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

+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;