[英]C# Winforms: Is it possible to have a function in a form called from the main Program.cs?
[英]How do I change the content of a WinForms label from the Program.cs main method?
所以我在我的主要方法中有一个启动例程,它检查以确保 .txt 文件中有内容。
FileInfo fInfo = new FileInfo(DataDir);
if (fInfo.Length < 64)
{
//Do stuff here if file is not long enough
}
我希望能够在我的 WinForms 应用程序上制作一个标签来显示一些文本,并且我想让一些控件变灰,但我似乎无法找到一种方法来引用所述标签/控件或表单中的任何对象事情。 我是初学者,我正在努力解决这个问题。
在您的表单中,声明一个bool
字段并在表单的构造函数中对其进行初始化:
public class MyForm : Form {
private bool _fileNotLongEnough;
public MyForm(bool fileNotLongEnough) {
_fileNotLongEnough = fileNotLongEnough;}
现在在表单后面,你可以使用这个字段的值来决定是否做事情。
在您的Main
方法中,您已经在构建表单。 这一次,传递一个bool
:
FileInfo fInfo = new FileInfo(DataDir);
Application.Run(new MyForm(fInfo.Length < 64));
如果您希望能够从Main()
方法使用您的Form
对象,您需要传入一个对象而不是使用new
关键字。
这是您通常看到的(Visual Studio 生成此代码)。
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
您可以做什么来处理表单对象。
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 myForm = new Form1(); //create the object here
//you can work with the form here
Application.Run(myForm); //pass in the form
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.