控制台和表单合二为一,数据传输

本文关键字:数据传输 合二为一 表单 控制台 | 更新日期: 2023-09-27 18:35:58

有一个代码表示控制台应用程序,我已经为表单完成了新线程并在新线程上显示自定义表单,我也尝试了某种数据传输,但我没有成功。

程序.cs代码...

class Program {
    public static CustomForm _customForm {
        get {
            return customForm;
        }
        set {
            customForm = value;
            customForm.Show();
        }
    }
    private static CustomForm customForm;
    /// <summary>
    /// Static method which constains all the magic for the console!
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args) {
        // Declaring Thread for the FormThread.
        Thread formThread = new Thread(new ThreadStart(FormThread));
        // Fires out the work of the thread.
        formThread.Start();
        Console.ReadKey();
        // And console is still running?
        // Thread formThread is still running too, thats the reason bruh!
    }
    /// <summary>
    /// Static method which constains all the magic for the form!
    /// </summary>
    static void FormThread() {
        customForm.lbl.Text = "Yolo, it wurks!";
        Application.Run(new CustomForm());
    }
}

自定义表单.cs代码...

public partial class CustomForm : Form {
    public string lblText {
        get {
            return lbl.Text;
        }
        set {
            lbl.Text = value;
        }
    }
    /// <summary>
    /// Just initializer, something what we'll never understand.
    /// </summary>
    public CustomForm() {
        InitializeComponent();
    }
    /// <summary>
    /// When the form is loaded.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnLoad(object sender, EventArgs e) {
        Program._customForm = this;
    }
}

我唯一想做的是调用 lbl 的 text 属性并在程序中设置一些值.cs,而不是在自定义表单中.cs

有时表单不会显示或表单中的 lbl 不会更改。

控制台和表单合二为一,数据传输

customForm.lbl.Text = "Yolo, it wurks!";

创建CustomForm之前执行。

可能需要在 main 中创建表单并将其传递给Application.Run(CustomForm);

   static void Main(string[] args) {
        // Declaring Thread for the FormThread.
        Thread formThread = new Thread(new ThreadStart(FormThread));
        // Fires out the work of the thread.
        customForm = new CustomForm();
        formThread.Start();
        Console.ReadKey();
        // And console is still running?
        // Thread formThread is still running too, thats the reason bruh!
    }

此外,不能从其他线程更改控件属性。要从其他线程更改属性,请使用Invoke方法。

 public partial class CustomForm : Form {
     public string lblText
        {
            get
            {
                return lbl.Text;
            }
            set
            {
                if (lbl.InvokeRequired)
                    lbl.Invoke((MethodInvoker) (() => lbl.Text = value));
                else
                    lbl.Text = value;
            }
        }
 }