0

我有以下 C# 代码:

using System;
using System.Windows.Forms;
namespace WinFormErrorExample 
{
    public partial class Form1 : Form
    {
        public static Form1 Instance;
        public Form1()
        {
            Instance = this;
            InitializeComponent();
        }

        public void ChangeLabel1Text(String msg)
        {
            if (InvokeRequired)
                Invoke(new Action<String>(m => label1.Text = m), new object[] {msg});
            else
                label1.Text = msg;
        } 

        static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
                Instance.ChangeLabel1Text("cool");
            }
        }
   }
}

当我打电话Instance.ChangeLabel1Text("cool");时,GUI 中什么也没有发生。

这是我构建的一个小程序,用于在更大的程序中显示我的问题。

为什么 GUI 没有更新?

4

3 回答 3

2

The call to

Application.Run(new Form1());

is blocking your application until the Form1 closes. So your subsequent line is not executed until you try to close

Of course, if you just want to test the functionality of the Instance call then remove that line after the Application.Run. Instead you need to create a separate thread that tries to call that method on the Form1 current instance

于 2013-10-01T09:42:17.227 回答
0

这样做,

首先将文本设置为文本框控件,然后Run()

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
form.Controls["ChangeLabel1Text"].Text = "cool";
Application.Run(form);
于 2013-10-01T09:48:12.943 回答
0

Application.Run(new Form1());方法调用执行在当前线程上运行标准应用程序消息循环。因此,该行将Instance.ChangeLabel1Text("cool");在应用程序关闭时执行。

为什么不更改构造函数内的标签文本?不需要静态变量。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        ChangeLabel1Text("Hello!");
    }
}
于 2013-10-01T10:51:17.280 回答