简体   繁体   English

如何从Program类访问Form1公共功能

[英]how to access Form1 public function from the Program class

I'm trying to create a function that can be called from the "Program" class that could call the AppendText method of the textBoxes in my form. 我正在尝试创建一个可以从“程序”类调用的函数,该函数可以在表单中调用textBoxes的AppendText方法。 The goal at the end is to use this function as a replacement to the Console.WriteLine so I need to be able to pass a string to that function so it appends that specific bit of text. 最后的目标是使用此函数替代Console.WriteLine,因此我需要能够将字符串传递给该函数,以便它附加该特定的文本位。

My first instinct was to create a public method in my Form1 class that I could then call from the "Program". 我的第一个直觉是在Form1类中创建一个公共方法,然后可以从“程序”中调用该方法。 Here it is : In the Form1 class : 在Form1类中:

public void Add(String message)
        {
            textBox1.AppendText(message + Environment.NewLine);
        }

The weird thing is that when I call that method from the Form1 class, it works fine but when I call it from the Program class, nothing happens, even tho the method is public. 奇怪的是,当我从Form1类调用该方法时,它可以正常工作,但是当我从Program类调用该方法时,即使该方法是公共的,也没有任何反应。

Calling the following doesn't do any thing and my form appears but the textbox is empty. 调用以下命令不会执行任何操作,并且会显示我的表单,但文本框为空。

static void Main()
        {        
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form1 mainForm = new Form1();
            Application.Run(mainForm);
            mainForm.Add("hello world");
        }

but adding that function to the constructor of Form1 works and the textBox appears with the text in 但是将该函数添加到Form1的构造函数中,并且textBox出现,其中的文本

public Form1()
        {
            InitializeComponent();
            this.Add("hello");
        }

I'm confused as to why a function would behave differently from inside the class or outside when the code compile fine and doesn't throw any error. 我对为什么当代码编译良好并且不引发任何错误时函数为什么在类内部或外部行为有所不同感到困惑。

When you call Application.Run, control enters in a loop, so, the next line only executes when the app exits 当您调用Application.Run时,控制进入一个循环,因此,下一行仅在应用程序退出时执行

https://docs.microsoft.com/es-es/dotnet/api/system.windows.forms.application.run?view=netframework-4.7.2 https://docs.microsoft.com/es-es/dotnet/api/system.windows.forms.application.run?view=netframework-4.7.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM