c# - 为什么我不能在主程序中与表单对象进行交互?

标签 c# winforms

这应该非常简单,但我很难看到任何结果。

我有以下表单代码:

//Form1.cs
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 NotepadRW
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected TextBox textReadInfo;
        public void SetReadInfo(String str)
        {
            txtReadInfo.Text = str;
        }
    }
}

我还有如下程序代码:

//Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NotepadRW
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form1 form1 = new Form1();
            Application.Run(form1);

            form1.SetReadInfo("Hi");

        }
    }
}

结果如下:

Blank Form

为什么它不显示我提供的字符串?我是否没有正确理解该程序如何与 Windows 窗体一起工作?当调用 Form1 的新实例时,Program.cs 的 Main() 方法的执行是否停止?

注意:我已经用文本框和富文本框试过了。相同的结果。

加分项: 我是否正确遵循封装?我打算将文本框修改为可公开访问(这会起作用),但我认为这是“正确”的做法。

最佳答案

虽然从the documentation看不明显, Application.Run(Form) 方法 block 。您可以从以下引用中推断出这一点:

The Dispose method of the Form class will be called prior to the return of this method.

这意味着表单将执行它的操作,并且必须在 Run 返回之前完成它的操作。即,它会阻塞。

不过,您可以通过调换顺序来完成您想要的。而不是

Form1 form1 = new Form1();
Application.Run(form1);
form1.SetReadInfo("Hi");

尝试

Form1 form1 = new Form1();
form1.SetReadInfo("Hi");
Application.Run(form1);

关于c# - 为什么我不能在主程序中与表单对象进行交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46611409/

相关文章:

c# - 如何在 EF 设置中仅从 Web.Config 获取提供程序连接字符串?

c# - 使用自定义图像按钮在 RichTextBox 中显示图像

c# - 如何设置模态窗体的所有者属性?

面向.NET Core 3.1的C++/CLI

C# Form.TransparencyKey 对不同颜色的工作方式不同,为什么?

c# - 进行大量 PropertyUpdates 时避免 UI 锁定

c# - 在Ilist中使用Func,为什么是lambda表达式?

c# - 通过线程以一定的时间间隔执行任务一定次数

c# - 使用 c# 测量 tcp 上的数据传输速率

c# - 从 WM_SIZE 消息更改表单大小