这应该非常简单,但我很难看到任何结果。
我有以下表单代码:
//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");
}
}
}
结果如下:
为什么它不显示我提供的字符串?我是否没有正确理解该程序如何与 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/