在 Application.Run() 之后更新表单

编程入门 行业动态 更新时间:2024-10-28 08:16:40
本文介绍了在 Application.Run() 之后更新表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我想要做的

// pseudo code Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 myForm = new Form1(); Application.Run(myForm); while(true) { string a = readline(); } form1.show(a)

换句话说,我需要表单总是显示输入.但上面的代码将在Application.Run(myForm);"之后停止.我不在 form1 类中编写此类代码的原因是代码的主要部分运行在用 F# 编写的机器学习引擎上,并且因为 F# 没有好的视觉设计器.所以我试图创建一个简单的 form1.dll,并使用它来绘制随时间变化的结果.所以我的问题是我只能初始化表单,但我不能随着时间的推移更新它.任何提示将不胜感激.

In other words , I need the form always show the input. but the code above will stop after 'Application.Run(myForm);'. The reason I don't write such code in the form1 class is the main part of code is run on a machine learning engine written in F#, and because F# doesn't have a good visual designer. So I am trying to create a simple form1.dll, and use it to plot the result over time. So my problem is I only can initialise the form, but I can't update it over time. Any hints will be appreciated.

推荐答案

您正在尝试同时做两件事,因此您的应用程序应该通过使用 2 个线程来反映这一点.接下来,Form的Show()方法不接受字符串,所以需要自己实现方法.

You're trying to do 2 things at the same time, so your application should reflect that by using 2 threads. Next, the Form's Show() method does not accept a string, so you need to implement your own method.

这是一个 C# 2.0 WinForms 解决方案.程序运行线程并处理控制台输入:

Here's a C# 2.0 WinForms solution. The program runs the thread and processes the console input:

static class Program { [STAThread] private static void Main() { // Run form in separate thread var runner = new FormRunner(); var thread = new Thread(runner.Start) {IsBackground = false}; thread.Start(); // Process console input while (true) { string a = Console.ReadLine(); runner.Display(a); if (a.Equals("exit")) break; } runner.Stop(); } }

FormRunner 负责线程调用:

The FormRunner takes care about thread invocation:

internal class FormRunner { internal Form1 form = new Form1(); internal void Start() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(form); } private delegate void StopDelegate(); public void Stop() { if (form.InvokeRequired) { form.Invoke(new StopDelegate(Stop)); return; } form.Close(); } private delegate void DisplayDelegate(string s); public void Display(string s) { if (form.InvokeRequired) { form.Invoke(new DisplayDelegate(form.Display), new[] {s}); } } }

而 Form1 只需要显示一些东西:

And Form1 just needs something to display:

public void Display(string s) { textBox1.Multiline = true; textBox1.Text += s; textBox1.Text += Environment.NewLine; }

更多推荐

在 Application.Run() 之后更新表单

本文发布于:2023-06-04 21:17:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/505230.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   Application   Run

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!