Corey Thompson
Corey Thompson

Reputation: 398

Creating a form on a new thread from console

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.

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)

Upvotes: 4

Views: 1002

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

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();

Upvotes: 3

Related Questions