I have a WinForms application that I'd like to have ability to run as a console application too (with 2 command-line arguments).
I tried the approach from this question Behavior in WinForm/Console Hybrid Application. But in this case, the methods of the FormMain.cs (FormMain class) are not accessible from the Program class (Program.cs).
How should I modify the code to be able to execute the FormMain.cs methods from the Program.cs?
UPD
The Program.cs code is
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 ???
}
}
}
}
The FormMain.cs code (i have reduced it a bit) is
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;
}
}
}
You may be looking at this backward: Instead of hoping to get access to your useful functions found in Form.cs - if they're that useful - you should, instead, move them to an external location where you can control their accessibility more easily.