-2

我有一个 WinForms 应用程序,我也希望它能够作为控制台应用程序运行(带有 2 个命令行参数)。

我尝试了这个问题Behavior in WinForm/Console Hybrid Application的方法。但在这种情况下,不能从 Program 类 (Program.cs) 访问 FormMain.cs(FormMain 类)的方法。

我应该如何修改代码才能从 Program.cs 执行 FormMain.cs 方法?

UPD

Program.cs代码是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Feature
{

internal static class NativeMethods
{
    [DllImport("kernel32.dll")]
    internal static extern Boolean AllocConsole();
}

static class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            // run as windows app
            Application.EnableVisualStyles();
            Application.Run(new FormMain(args));
        }
        else
        {
            // run as console app
            NativeMethods.AllocConsole();
            //??? How to access the methods of FormMain here ???
        }
    }
}

}

FormMain.cs代码(我已经减少了一点)是

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Xml.XPath;
using System.Xml;
using Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace Feature
{
public partial class FormMain : Form
{
    public FormMain(string[] Args)
    {
        InitializeComponent();
    }

    public ArrayList Errors = new ArrayList();

    public ArrayList GetDirectoriesRecursively(string startPath)
    {
        string[] oNewDirectories = Directory.GetDirectories(startPath);
        ArrayList oDirectories = new ArrayList();
        ArrayList oDirectoriesNewList;

        foreach (string oCurrent in oNewDirectories)
        {
            oDirectories.Add(oCurrent);
            oDirectoriesNewList = GetDirectoriesRecursively(oCurrent);
            if (oDirectoriesNewList.Count > 0) oDirectories.AddRange(oDirectoriesNewList);
        }
        return oDirectories;
    }

    public ArrayList GetFilesInFolder(string startPath, string pattern)
    {
        string[] oNewFiles = Directory.GetFiles(startPath, pattern);
        ArrayList oFiles = new ArrayList();
        foreach (string oCurrent in oNewFiles)
            oFiles.Add(oCurrent);
        return oFiles;
    }
}

}

4

1 回答 1

2

您可能会向后看:与其希望访问您在 Form.cs 中找到的有用函数(如果它们很有用的话),不如将它们移动到可以更轻松地控制其可访问性的外部位置.

于 2012-04-11T14:55:44.793 回答