【问题标题】:How to output a parameter in a form application in C#?如何在 C# 中的表单应用程序中输出参数?
【发布时间】:2017-04-24 15:19:37
【问题描述】:

我正在尝试运行一个应用程序(编译/构建的 C# 表单程序),同时将参数传递给它:

Process process = Process.Start(@"[insertDirectory]", "HelloWorld");

在入口点/main方法的括号中:

-命令行应用程序有:

string[] args

一个表格有:

object sender, EventArgs e

令我惊讶的是,我不能像使用 string[] args 一样使用 EventArgs e

可以在控制台应用程序中使用args[0] 输出参数。如何在表单应用程序中做同样的事情?

更正

object sender, EventArgs e

在 _load 括号中。该方法不是入口点。请参阅约翰的/最佳答案。

【问题讨论】:

    标签: c# forms parameters arguments


    【解决方案1】:

    您的程序的入口点仍然是Program.cs 中的Main()。您可以简单地添加string[] args

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string [] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
    

    然后您可以**用new Form1(args) 替换new Form1(),然后更新您的表单构造函数:

    public Form1(string [] args)
    {
        InitializeComponent();
    }
    

    ** 获得参数后的实现细节完全取决于您。您可以通过多种方式将参数注入表单。

    【讨论】:

    • 另请注意,OnLoad 方法不是“启动”程序的方法,而是在表单加载时调用的事件。所以它与启动时传递参数无关。
    • @itay_421 确实。
    • 上面的代码是指控制台应用程序吗?我将其复制并粘贴到表单代码中,并出现错误提示“程序定义了多个入口点。使用 /main 编译以指定包含入口点的类型。”
    • Rahul,看看 Program.cs。您的表单不是应用程序的入口点。
    • 我现在明白你的意思了。未来的访问者:在列出所有项目(表单、类等)的 Visual Studio 右侧,有一个 Program.cs 文件。打开它并在主括号中添加“string[] args”。然后在您的表单的括号中添加“args”。然后在包含“InitializeComponent()”的公共方法的括号内添加“string[] args”。中提琴!
    猜你喜欢
    • 1970-01-01
    • 2010-11-17
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    相关资源
    最近更新 更多