[英]Calling `Main` method of a console application from a form application (by a button click event)
How can I access and run a console application from a windows form , which is part of the same project. 如何从Windows窗体访问和运行控制台应用程序,该窗体是同一项目的一部分。 I have a windows form and a console application.
我有一个Windows窗体和一个控制台应用程序。 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. 我认为我可以发布控制台应用程序,然后使用
Process.Start(path to console app)
但这不是我想要的。 I want to access and use the Main
method of the console application in my form project. 我想在我的表单项目中访问和使用控制台应用程序的
Main
方法。 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.
InvalidOperationException未处理当任一应用程序没有控制台或从文件重定向控制台输入时,无法读取键。 Try Console.Read.
试试Console.Read。
private void buttonApplication_Click(object sender, EventArgs e)
{
Ch15Extra_2.Program.Main();
}
Here are the methods. 这是方法。
ConsoleApp: ConsoleApp:
namespace Ch15Extra_2
{
public class Program
{
public static void Main()
{
Console.WriteLine("Here the app is running");
Console.ReadKey();
}
}
}
Form1: Form1中:
private void buttonApplication_Click(object sender, EventArgs e) { }
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: 如果您需要在没有WinForms应用程序的情况下运行您的控制台应用程序,有时您想在不运行控制台应用程序的情况下执行某些控制台代码,我建议您:
You can divide your solution into three parts. 您可以将解决方案分为三个部分。
Link a dll to first and to the second projects. 将dll链接到第一个项目和第二个项目。
Then if you need to run shared code from WinFomrs app, you can do: 然后,如果您需要从WinFomrs应用程序运行共享代码,您可以执行以下操作:
private void buttonApplication_Click(object sender, EventArgs e)
{
var shared = new SharedClass();
shared.Run();
}
SharedClass
will be implemented in the third project. SharedClass
将在第三个项目中实现。 You can call it from console app too. 你也可以从控制台应用程序调用它。
upd UPD
Project 1 : ClassLibrary. 项目1:ClassLibrary。
public class SharedClass
{
public int DoLogic(int x)
{
return x*x;
}
}
Proj 2. WinForms. Proj 2. WinForms。 Has a Reference to Project 1
参考项目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 proj 3.控制台应用程序
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. 我刚检查过 - 它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.