Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run my Console Application code within a Windows Forms? [duplicate]

Tags:

c#

winforms

I made a Console Application with C# in VS.

I want to make a button, which runs some code. In this case, what I wrote in the Console Application. How would one go about that?

Basically I want to create a set of buttons, where each executes a specific task. How would I do this? How can I take that code I created earlier and have a button execute it?

like image 744
sofuzzeh Avatar asked Apr 01 '26 04:04

sofuzzeh


1 Answers

I can mention two options of many:

  1. Deal with your Console app as a DLL and reference it in your WinForm Runner App.
  2. Deal with your Console app as an EXE file and run it using Process.Start.

The first option will give you the ability to reach the methods while the second one will deal with it as a totally separate app with all its functionalities as a single application.

Example of the Second Option:

  1. Create a Solution with three projects as in the screenshot below.

Solution

  1. Suppose your Console App 1 code is
    using System;
        namespace SOC.ConsoleApp01
        {
            public class Program
            {
                public static void Main(string[] args)
                {
                    Console.WriteLine("Written from Console App 1");
                    Console.ReadLine();
                }
            }
        }

While the second is

using System;

namespace SOC.ConsoleApp02
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Written from Console App 2");
            Console.ReadLine();
        }
    }
}
  1. Now build the Console App1 and Console App 2 by right click on each of them in the solution explorer and click Build or ReBuild. Build

This will result in execution files generated like in the following screenshots: App 1 Exe file App 2 Exe file

  1. In your WinForm Project write the code of Subject buttons like this
    using System;
    using System.Diagnostics;
    using System.Windows.Forms;
    
    namespace SO.Console.Apps.Runner
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
        private void button1_Click(object sender, EventArgs e)
        {
            Process.Start(@"C:\REPOS\SO.Console.Apps.Runner\SOC.ConsoleApp01\bin\Debug\SOC.ConsoleApp01.exe");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Process.Start(@"C:\REPOS\SO.Console.Apps.Runner\SOC.ConsoleApp02\bin\Debug\SOC.ConsoleApp02.exe");
        }
    }
    }

the result is Result

like image 151
Useme Alehosaini Avatar answered Apr 03 '26 18:04

Useme Alehosaini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!