c# - 子表单运行时防止初始表单出现 "refreshing"

标签 c# .net winforms

我有以下(精炼)代码:

表格1

public partial class Form1 : Form
{
    GetIP getIP;
    string deviceIP = "";

    public Form1()
    {
        InitializeComponent();

        if (deviceIP == "") 
        {
            getIP = new GetIP();
            var result = getIP.ShowDialog();
            if (result == DialogResult.OK)
            {
                string ip = getIP.IPAddress;
                deviceIP = ip;
            }
        }
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        form2 = new Form2();
        form2.ShowDialog();
    }
}

获取IP

public partial class GetIP : Form
{
    public string IPAddress { get; set; }
    public GetIP()
    {
        InitializeComponent();
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
        IPAddress = txtIPAddress.Text;
        DialogResult = DialogResult.OK;
        Close();
    }
}

表格2

public partial class Form2 : Form
{
    Form1 form1 = new Form1(); // oops...this might be it?

    public Form2(string deviceData)
    {
        InitializeComponent();
        // Force CRLF (\r\n) on all newline instances
        deviceData = deviceData.Replace("\r\n", "\n");
        deviceData = deviceData.Replace("\r", "\n"); 
        deviceData = deviceData.Replace("\n", "\r\n");
        txtdeviceData.Text = deviceData;
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
}

我的问题是,每当 Form2 尝试打开时,Form1 似乎都会刷新。这会导致 GetIP 再次运行(这也意味着 deviceIP 被重新初始化回“”)。 GetIP 完成后,Form2 才会打开。

deviceIP == "" 的检查是我解决问题的尝试,但似乎变量初始化也重新运行,从而使我的检查无效。

是否有办法防止 Form1 刷新,或者至少有办法专门防止 GetIP 再次运行?

更新
嗯,我刚刚注意到我有似乎是剩余的代码行,它创建了一个 Form1 实例...

最佳答案

public partial class Form2 : Form
{
    Form1 form1 = new Form1(); // oops...this might be it?

是的,就是“哎呀”。

如果 Form2 需要引用 Form1,请尝试通过构造函数传递它:

public partial class Form2 : Form
{
  Form1 form1 = null;

  public Form2(Form1 f1, string deviceData) {
    InitializeComponent();
    form1 = f1;
    // etc, etc.
  }

关于c# - 子表单运行时防止初始表单出现 "refreshing",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54580266/

相关文章:

c# - 在 WinForms 的 ListView 中显示当前/选定的项目

c# - 将窗口保持在顶部并在 WinForms 中窃取焦点

c# - 当 ProcessStartInfo.CreateNoWindow 设置为 true 时,为什么 RedirectStandardInput 没有效果?

c# - 通过单击第 3 方 .NET 应用程序的按钮自动用户登录 PHP 网站

c# - 使用 jquery、ajax 和 asp.net 的评论框?

.net - BasicHttpsBinding 和具有传输安全性的 WsHttpBinding 有什么区别?

c# - 如何向数据库中插入数据? - 用户定义的类

C# WPF-组合框

c# - 在 Expression 中调用 Any 并传递委托(delegate)

c# - 如何使用 DevExpress WinForms TextEdit 作为密码输入(带星号)?