使WinForms应用程序WinForms / Console混合

时间:2012-04-11 14:44:26

标签: c# winforms console hybrid

我有一个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;
    }
}

}

1 个答案:

答案 0 :(得分:2)

你可能正在向后看:不是希望能够访问Form.cs中的有用功能 - 如果它们非常有用 - 你应该将它们移动到一个你可以控制它们的外部位置可访问性更容易。