Michael C wrote:
Is it possible to have an app that is both a console app and a windows app?
If there are no command line switches then it will run as a console app, if
there are command line switches then it will be a windows app. If I make it
a windows app then I can't write to the console. If I make it a console app
then it starts a console if the user runs it from the start menu so from
what I see it's not possible.
It is not easy, but if you are wiling to code for it, then it
can be done.
See the code below (it is not production grade, but it is a
starting point).
Arne
=============== =============== ===============
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()
{
InitializeCompo nent();
}
public void InitializeCompo nent()
{
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(lb l);
ResumeLayout(fa lse);
}
}
public class MyConsole : IDisposable
{
private const uint STD_INPUT_HANDL E = 0xfffffff6;
private const uint STD_OUTPUT_HAND LE = 0xfffffff5;
private const uint STD_ERROR_HANDL E = 0xfffffff4;
[DllImport("kern el32.dll")]
public static extern bool AllocConsole();
[DllImport("kern el32.dll")]
public static extern bool FreeConsole();
[DllImport("kern el32.dll")]
public static extern int GetStdHandle(ui nt nStdHandle);
[DllImport("kern el32.dll")]
public static extern bool WriteConsole(in t hConsoleOutput,
string lpBuffer,
int nNumberOfCharsT oWrite,
ref int
lpNumberOfChars Written,
int lpReserved);
[DllImport("kern el32.dll")]
public static extern bool ReadConsole(int hConsoleInput,
StringBuilder lpBuffer,
int nNumberOfCharsT oRead,
ref int lpNumberOfChars Read,
int lpReserved);
private int stdin;
private int stdout;
public MyConsole()
{
AllocConsole();
stdin = GetStdHandle(ST D_INPUT_HANDLE) ;
stdout = GetStdHandle(ST D_OUTPUT_HANDLE );
}
public void WriteLine(strin g s)
{
int len = 0;
WriteConsole(st dout, s + "\r\n", s.Length + 2, ref len, 0);
}
public string ReadLine()
{
int len = 0;
StringBuilder sb = new StringBuilder() ;
ReadConsole(std in, 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.WriteLi ne("This is a console app");
}
}
}
}
}