从表单应用程序调用控制台应用程序的 `Main` 方法(通过按钮单击事件) [英] Calling `Main` method of a console application from a form application (by a button click event)
问题描述
如何从属于同一项目的 Windows 窗体访问和运行控制台应用程序.我有一个 Windows 窗体和一个控制台应用程序.我认为我可以发布控制台应用程序,然后使用 Process.Start(path to console app)
但这不是我想要的.我想在我的表单项目中访问和使用控制台应用程序的 Main
方法.单击按钮即可运行此方法.
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.
这会产生以下错误.
InvalidOperationException 未处理当任一应用程序没有控制台时无法读取密钥或者当控制台输入已从文件重定向时.试试 Console.Read.
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();
}
这里是方法.
控制台应用程序:
namespace Ch15Extra_2
{
public class Program
{
public static void Main()
{
Console.WriteLine("Here the app is running");
Console.ReadKey();
}
}
}
表格 1:
private void buttonApplication_Click(object sender, EventArgs e) { }
推荐答案
如果你需要在没有 WinForms 应用的情况下运行你的控制台应用,并且有时你想在不运行控制台应用的情况下执行一些控制台代码,我有一个建议给你:
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.
- WinForms 部分
- 控制台部分
- DLL 库.
将 dll 链接到第一个和第二个项目.
Link a dll to first and to the second projects.
然后,如果您需要从 WinFomrs 应用程序运行共享代码,您可以:
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
将在第三个项目中实现.您也可以从控制台应用调用它.
SharedClass
will be implemented in the third project.
You can call it from console app too.
更新
项目 1:类库.
public class SharedClass
{
public int DoLogic(int x)
{
return x*x;
}
}
项目 2. WinForms.有对项目 1 的参考
Proj 2. WinForms. Has a Reference to Project 1
使用共享;
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();
}
}
}
项目 3. 控制台应用
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.
这篇关于从表单应用程序调用控制台应用程序的 `Main` 方法(通过按钮单击事件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!