4

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)

Corey Thompson
  • 398
  • 6
  • 18

1 Answers1

3

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();
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Excellent! Thanks! – Corey Thompson Dec 21 '16 at 13:11
  • On a related note, I kind of want to alter what goes on the form based on the command I enter... I realised I have to initialize the form and alter it within the same thread call - any ideas on a prettier way of doing this? Basically I don't like calling the same code multiple times with slightly different parameters... – Corey Thompson Dec 21 '16 at 13:13
  • I had the (theoretically) genius idea of basically creating a form and adding what I want, and having a function with your code above, taking a Form as a parameter - then the thread creates a new form which is a clone of the form passed - then shows the clone. Unfortunately I can't get it to add the controls on the form because it's being access from a separate thread... – Corey Thompson Dec 21 '16 at 13:22
  • You should change the form from the same thread which you create the form. So you can keep a reference to the form (for example `f` variable) and then using `Invoke` method do what you need. For example `f.Invoke(new Action(() => { f.Text = DateTime.Now.ToString(); }));`. – Reza Aghaei Dec 21 '16 at 13:26
  • There are many question in the site about accessing control from a different thread than UI thtread, for example [this one](https://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c). So I didn't add more details about it it the answer. – Reza Aghaei Dec 21 '16 at 13:27