Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run two winform windows simultaneously

Tags:

I have two C# winform (.NET 4.0) forms that each run separate but similar automated tasks continuously. Separate in that they are distinct processes/workflows, but similar enough in how they operate to share the same resources (methods, data models, assemblies, etc) in the project.

Both forms are complete, but now I'm not sure how to run the program so that each window opens on launch and runs independently. The program will be "always-on" when deployed.

This might seem a little basic, but most of my development experience has been web applications. Threading/etc is still a little foreign to me. I've researched but most of the answers I've found relate to user interaction and sequential use cases -- this will just be one system continuously running two distinct processes, which will need to interact with the world independently.

Potential solutions I've found might involve multi-threading, or maybe some kind of MDI, or a few folks have suggested the DockPanelSuite (although being in a super-corporate environment, downloading third party files is easier said than done).

static class Program {     /// <summary>     /// The main entry point for the application.     /// </summary>     [STAThread]     static void Main()     {         Application.EnableVisualStyles();         Application.SetCompatibleTextRenderingDefault(false);          // Rather than specifying frmOne or frmTwo,         // load both winforms and keep them running.         Application.Run(new frmOne());     } } 
like image 311
RJB Avatar asked Mar 08 '13 18:03

RJB


People also ask

Is Winforms multithreaded?

The . NET Framework has full support for running multiple threads at once.

How do I open a second form in Windows?

Now go to Solution Explorer and select your project and right-click on it and select a new Windows Forms form and provide the name for it as form2. Now click the submit button and write the code. When you click on the submit button a new form will be opened named form2.


1 Answers

You can create a new ApplicationContext to represent multiple forms:

public class MultiFormContext : ApplicationContext {     private int openForms;     public MultiFormContext(params Form[] forms)     {         openForms = forms.Length;          foreach (var form in forms)         {             form.FormClosed += (s, args) =>             {                 //When we have closed the last of the "starting" forms,                  //end the program.                 if (Interlocked.Decrement(ref openForms) == 0)                     ExitThread();             };              form.Show();         }     } } 

Using that you can now write:

Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MultiFormContext(new Form1(), new Form2())); 
like image 144
Servy Avatar answered Sep 30 '22 17:09

Servy