【问题标题】:C# Console App as a Windows FormC# 控制台应用程序作为 Windows 窗体
【发布时间】:2018-07-06 03:45:15
【问题描述】:

我在 Visual Studio 中以控制台应用程序的形式开始了一个项目,现在我发现我需要一个 UI(表单),但是当我运行该程序时,它是一个控制台。无论如何,我的控制台应用程序中的 Program.cs 代码是否可以通过按钮事件运行?

我的代码的Spinet:

    using System;
using System.Net.Sockets;
using System.IO;
public class Program
{

    public static string name = null;
    public static string userloc = null;
    public static string protocol = null;

    public static int Portal = 43;
    public static string Address = "whois.net.dcs.hull.ac.uk";

    static void Main(string[] args)
    {


        for (int i = 0; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "-h0":
                    protocol = "-h0";
                    break;

                case "-h1":
                    protocol = "-h1";
                    break;

                case "-p":
                    Portal = int.Parse(args[i + 1]);
                    ++i;
                    break;

表格代码:

namespace location
{
    public partial class Location : Form
    {
        public Location()
        {
            InitializeComponent();
        }

        private void updateBtn_Click(object sender, EventArgs e)
        {

        }
    }
}

【问题讨论】:

标签: c# winforms user-interface console-application


【解决方案1】:

您需要的大部分内容都在How do I convert a .NET console application to a Winforms or WPF application

然后您在 cmets 中询问“如何让表单上的按钮运行 Main() 代码?”。我假设您知道单击updateBtn 时将执行updateBtn_Click 方法,并且我假设您所说的按钮是“我的表单上的按钮”。

答案是您不希望按钮单击调用Program.Main,因为这是应用程序的入口点。

我也假设你想保留命令行参数,所以你需要将args的处理留在Program.Main中。

无论您的其余功能是什么,您都可以将其直接移动到您的表单中,即 updateBtn_Click 方法中。可能需要调整代码以从那里获取命令行参数的值,方法是在它们的名称前加上 Program. 前缀,因为它们都是静态的(例如 Program.Portal)。

这可能会满足您现在的要求。随着时间的推移,您会意识到将代码塞进“代码背后”(我刚刚告诉您这样做)并不是一个好主意。如果您重构代码,那么您将能够从命令行、WinForm 应用程序或 WPF 或 Web 应用程序使用您的功能。但也许现在已经足够了......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多