从控制台在新线程上创建表单 [英] Creating a form on a new thread from console

查看:101
本文介绍了从控制台在新线程上创建表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,无法解决.

I have an odd question which I haven't been able to find a solution to.

基本上,我有一个控制台应用程序.它需要命令,我可以根据这些命令确定操作.所有操作都涉及打开表单并显示某物.

Basically, I have a console application. It takes commands, which I determine actions from. All of the actions involve opening a form and displaying something.

当前,我能够输入命令,它可以正确确定操作并弹出一个表格,一切正常. 不幸的是,这样做的时候,表单背后的后台控制台实际上冻结了(我已经意识到它不再更新UI)-因此,如果我尝试在表单打开的情况下键入另一个命令,则直到发生任何事情我关闭表格.

Currently, I'm able to enter a command, it correctly determines the action and pops up a form and everything is okay. Unfortunately, in doing so, the console in the background behind the form essentially freezes (I've realised it just isn't updating the UI anymore) - so if I try and type another command while there's a form open, nothing will happen until I close the form.

我一直在寻找一个新的线程来运行表单,而我猜这是我要采用的路径-但我不知道如何做到这一点.导致错误(例如,来自单独线程的令人讨厌的非法访问错误).

I've been looking into creating a new thread for the form to run in which I guess is the path I need to take - but I can't figure out how to do that while not causing errors (e.g. that pesky illegal access from a separate thread error).

任何人都可以帮忙吗?

Can anyone help?

我应该从一开始就搞定一个表格,然后通过表格上的文本框输入我的命令吗? (似乎很烦人,但是至少我有一个可以调用其他东西的表单)

Should I cave and just set up a form from the get-go and make my commands be entered via a textbox on a form? (seems annoying, but at least I then have a form that can invoke other things)

推荐答案

您可以在控制台应用程序的另一个线程中打开表单,如下所示:

You can open forms from a console application in another thread like this:

var t = new Thread(() => {
    var f = new Form();
    f.ShowDialog();
});
t.SetApartmentState(ApartmentState.STA);
t.Start();

这篇关于从控制台在新线程上创建表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆