VS Code下C#开发获取WinForm的TextBox控件输入文本失败求助
问题根因
- 你在
FormLayout方法初始化控件时就立即读取textBox1.Text,此时用户还未进行任何输入,拿到的永远是空值;且lingua是方法内部局部变量,外部根本无法访问 Application.Run(form)是阻塞方法,只有当窗体关闭后才会执行后续代码,但你后续又二次调用了form.FormLayout(),会重新初始化控件,直接覆盖用户之前的输入内容FormLayout返回值为void,你尝试读取form.FormLayout().lingua属于语法错误,代码本身无法正常编译- 自定义动作方法
MyFunctionAsAction1中直接调用Main()会重复启动窗体消息循环,逻辑完全错误
修正后的实现代码
Form1类调整
public class Form1 : Form { private TextBox textBox1; private Button confirmBtn; // 公开属性,外部读取用户输入的文本 public string InputText => textBox1.Text; public void FormLayout() { this.Name = "Form1"; this.Text = "Form1"; this.Size = new System.Drawing.Size(200, 200); this.StartPosition = FormStartPosition.CenterScreen; // 初始化文本框 this.textBox1 = new TextBox(); this.textBox1.Location = new System.Drawing.Point(20, 20); this.textBox1.Size = new System.Drawing.Size(140, 23); // 新增确认按钮,用户点击后关闭窗体 this.confirmBtn = new Button(); this.confirmBtn.Text = "确认"; this.confirmBtn.Location = new System.Drawing.Point(20, 60); this.confirmBtn.Click += (s, e) => { this.DialogResult = DialogResult.OK; this.Close(); }; this.Controls.AddRange(new Control[] { textBox1, confirmBtn }); } }
入口与动作类调整
public class RegisterScriptMenu { [DeclareAction("Exporta_Traduzir")] public void MyFunctionAsAction1() { Form1 form = new Form1(); form.FormLayout(); // 启动窗体,等待用户关闭后再读取输入 if (form.ShowDialog() == DialogResult.OK) { string linguagem = form.InputText; // 此处写入拿到输入后要执行的业务逻辑 } } [STAThread] static void Main() { // 主入口需要启动窗体直接调用动作方法即可 new RegisterScriptMenu().MyFunctionAsAction1(); } }
核心调整说明
- 给Form1新增了公开的
InputText属性,外部可以安全读取文本框的输入内容 - 新增确认按钮,用户输入完成后点击按钮才会关闭窗体,保证读取的是用户输入后的内容
- 不再重复调用
FormLayout方法,避免控件被重置 - 将窗体启动逻辑放到动作方法内,拿到窗体返回结果后再读取输入值,符合WinForm的消息循环执行逻辑
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

