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