Calling the "Main" method of the console application from the form application (via the button click event)

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

This leads to the following error.

The InvalidOperationException error was unhandled. Unable to read keys if the application does not have a console or when console input was 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) { } 
+6
source share
1 answer

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

You can divide the solution into three parts.

  • WinForms Part
  • Console part
  • Dll library.

Link the dll to the first and second projects.

Then, if you need to run the generic code from the WinFomrs application, 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 also call it from the console application.


update

Project 1: ClassLibrary.

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

Proj 2. WinForms. Has a link to the 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 application

  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 just checked - it works.

+7
source

Source: https://habr.com/ru/post/926752/


All Articles