Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling `Main` method of a console application from a form application (by a button click event)

Tags:

c#

winforms

How can I access and run a console application from a windows form, which is part of the same project. I have a windows form and a console application. I think that I can publish the console application and then use Process.Start(path to console app) but this is not what I want. I want to access and use the Main method of the console application in my form project. This method would run at a click on a button.

This gives the following error.

InvalidOperationException was unhandled Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.

private void buttonApplication_Click(object sender, EventArgs e)
{
  Ch15Extra_2.Program.Main();
}

Here are the methods.

ConsoleApp:

namespace Ch15Extra_2
{
  public class Program
  {
    public static void Main()
    {
      Console.WriteLine("Here the app is running");
      Console.ReadKey();
    }
  }
}

Form1:

private void buttonApplication_Click(object sender, EventArgs e) { }
like image 640
somethingSomething Avatar asked Oct 02 '12 12:10

somethingSomething


1 Answers

If you need to run your console app without WinForms app, and sometimes you want to execute some console code without running a console app, I have a suggestion for you:

You can divide your solution into three parts.

  1. WinForms part
  2. Console part
  3. Dll library.

Link a dll to first and to the second projects.

Then if you need to run shared code from WinFomrs app, you can do:

private void buttonApplication_Click(object sender, EventArgs e)
{
    var shared = new SharedClass();
    shared.Run();
}

SharedClass will be implemented in the third project. You can call it from console app too.


upd

Project 1 : ClassLibrary.

public class SharedClass
{
    public int DoLogic(int x)
    {
        return x*x;
    }
}

Proj 2. WinForms. Has a Reference to Project 1

using Shared;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        TextBox textBox = new TextBox();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var shared = new SharedClass();
            textBox.Text = shared.DoLogic(10).ToString();
        }
    }
}

proj 3. Console App

    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Here the app is running");
            var shared = new Shared.SharedClass();
            Console.WriteLine(shared.DoLogic(10));
            Console.ReadKey();
        }
    }

I've just checked - it works.

like image 187
Anton Sizikov Avatar answered Sep 21 '22 02:09

Anton Sizikov