[英]Console and form in one and data transfer?
There is a code represents Console Application where I've done new Thread for the form and displaying a CustomForm on our new thread, I've also tried some kind of data transfer but I haven't successed. 有一个代表控制台应用程序的代码,其中我为表单完成了新的线程并在我们的新线程上显示了CustomForm,我也尝试了某种数据传输,但没有成功。
Program.cs code ... Program.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());
}
}
CustomForm.cs code ... 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;
}
}
The only thing I want to do is call the lbl's text property and set some value in a program.cs, not in the customform.cs 我唯一想做的就是调用lbl的text属性,并在program.cs中而不是在customform.cs中设置一些值。
Sometimes form wont to show or the lbl in the form isn't changed. 有时表单不会显示,或者表单中的lbl不会更改。
customForm.lbl.Text = "Yolo, it wurks!";
executes before you are creating CustomForm
. 在创建CustomForm
之前执行。
Probably, you need to create your form in the main and pass it into Application.Run(CustomForm);
可能需要在主体中创建表单并将其传递到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!
}
Also, you can't change a control property from other threads. 另外,您不能从其他线程更改控件属性。 In order to change property from other thread use Invoke
method. 为了从其他线程更改属性,请使用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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.