// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; namespace E { public class MainForm : Form { private Label lbl; public MainForm() { InitializeComponent(); } public void InitializeComponent() { lbl = new Label(); SuspendLayout(); lbl.Location = new Point(50, 50); lbl.Size = new Size(200, 25); lbl.Text = "This is a GUI app"; Text = "Main form"; Size = new Size(300, 300); Controls.Add(lbl); ResumeLayout(false); } } public class MyConsole : IDisposable { private const uint STD_INPUT_HANDLE = 0xfffffff6; private const uint STD_OUTPUT_HANDLE = 0xfffffff5; private const uint STD_ERROR_HANDLE = 0xfffffff4; private const uint ATTACH_PARENT_PROCESS = 0xffffffff; [DllImport("kernel32.dll")] public static extern bool AttachConsole(uint dwProcessId); [DllImport("kernel32.dll")] public static extern bool AllocConsole(); [DllImport("kernel32.dll")] public static extern bool FreeConsole(); [DllImport("kernel32.dll")] public static extern int GetStdHandle(uint nStdHandle); [DllImport("kernel32.dll")] public static extern bool WriteConsole(int hConsoleOutput, string lpBuffer, int nNumberOfCharsToWrite, ref int lpNumberOfCharsWritten, int lpReserved); [DllImport("kernel32.dll")] public static extern bool ReadConsole(int hConsoleInput, StringBuilder lpBuffer, int nNumberOfCharsToRead, ref int lpNumberOfCharsRead, int lpReserved); private int stdin; private int stdout; public MyConsole() { /* if(!AttachConsole(ATTACH_PARENT_PROCESS)) { AllocConsole(); } */ AllocConsole(); stdin = GetStdHandle(STD_INPUT_HANDLE); stdout = GetStdHandle(STD_OUTPUT_HANDLE); } public void WriteLine(string s) { int len = 0; WriteConsole(stdout, s + "\r\n", s.Length + 2, ref len, 0); } public string ReadLine() { int len = 0; StringBuilder sb = new StringBuilder(); ReadConsole(stdin, sb, 256, ref len, 0); return sb.ToString(0, sb.Length - 2); } public void Dispose() { FreeConsole(); } } public class MainClass { [STAThread] public static void Main(string[] args) { if(args[0] == "GUI") { Application.Run(new MainForm()); } else if(args[0] == "Console") { using(MyConsole console = new MyConsole()) { console.WriteLine("This is a console app"); string s = console.ReadLine(); console.WriteLine(s); } } } } }