gpt4 book ai didi

c# - 如何访问其他类中的控件

转载 作者:行者123 更新时间:2023-11-30 15:04:45 24 4
gpt4 key购买 nike

我正在学习 C#,我需要的是访问来自其他类的表单的控制(相同的命名空间)。

我知道这里有很多关于这个主题的帖子,但没有找到“傻瓜”的完整解决方案,所以我在这里写下我的想法,请告诉我 - 这是正确的方法吗?

背景:我的应用程序中有一些“调试”表单,我需要所有其他表单才能将其事件记录到此表单中。有一些 ListBox 控件,其中写入了来自其他表单的所有日志。当我(或我的一位没有 Visual Studio 的测试员 friend )玩应用程序时发生了一些不好的事情,我可以查看该调试表单以查看所有详细日志,了解在那个“错误时刻 '.

我的应用程序主要形式 (frmMain):

namespace myNamespace {

public partial class frmMain : Form {

private frmDebug debug; // frmDebug is declared in other class
// we will hold reference to frmDebug form in 'debug'

public frmMain() { // constructor of the main form 'frmMain'
InitializeComponent();
debug = new frmDebug(); // we create new instance of frmDebug immediately when
} // our main form is created (app started) and whole time
// of running this app we can access frmDebug from
// within frmMain through 'debug' variable


// clicking button 'btnLoggingTest', the log is written
// in the 'frmDebug' form even if it is closed (not visible)
private void btnLoggingTest_Click(object sender, EventArgs e) {
debug.Log("log this text for me please");
}

// Click handler of the button 'btnShowDebug' :
private void btnShowDebug_Click(object sender, EventArgs e) {
debug.ShowDialog(); // here we can show frmDebug (in 'modal' style)
} // just to see what log-information is written there


} // frmMain class

} // namespace



这是类 frmDebug 本身的代码:(窗体上只有一个Listbox)

namespace myNamespace {
public partial class frmDebug : Form {

public frmDebug() {
InitializeComponent();
}

public void Log(string txt) { // this is the actual 'Log' function (or method)
this.listBox1.Items.Add(txt);
Application.DoEvents(); // if the logging takes place in some
} // computing-intensive 'loop' or function,
// (or in my case FTP login and upload process)
// 'DoEvents' ensures every log appears immediately
// after the 'Log()' was called. Otherwise all logs
// would appear together at once, as soon as the
// computing-intensive 'loop' is finished

} // class frmDebug

} // namespace



我的胃里有一种奇怪的感觉,我做错了,所以请告诉我如何正确地做 :)
如果没问题,希望它能帮助像我这样的人。

谢谢!

最佳答案

您的应用程序可能有一个名为“Program”的类。在那里你会找到代码

var mainForm = new frmMain();
Application.Run(frmMain);

在这个类中为调试窗体创建一个静态属性

public static frmDebug DebuggingForm { get; private set; }

像这样更改启动代码

DebuggingForm = new frmDebug();
var mainForm = new frmMain();
Application.Run(frmMain);

您可以从其他类(class)访问此表单

Program.DebuggingForm.Log("log this text for me please");         
Program.DebuggingForm.Show();

关于c# - 如何访问其他类中的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9831930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com