Michael said:
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()
{
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;
[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()
{
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");
}
}
}
}
}