Hello,
I have a console based app. I want to convert it to a windows form, but if run from the command line, I would like it to write out the responses to the command line and not invoke the GUI. If launched without any arguments, the GUI starts up.
Any ideas?
Loading
Sam HobbsPosted Mar 1, 2010, 5:27 PM
Although I am not sure what you would do to determine whether to show a form. I assume that the presence or absence of a command line is not sufficient for determining whether to show a form. So I will leave that for you and Raaj to figure out.
Sam HobbsPosted Mar 1, 2010, 4:23 PM
Another possibility is to simply use a command-line option that determines whether the program shows a form or not. The program can be built as a console program but show a form if it is executed without the command-line option, or something such as that. The problem with that is that there will be a console showing even if the application uses a form for everything.
Another possibility is to put all the main logic in a class library and then write two programs; a console and a GUI that use the class library.
Raaj KumarPosted Mar 1, 2010, 7:27 AM
Try this code,
using System.Runtime.InteropServices;
static class Program
{
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
[STAThread]
static void Main(string[] args)
{
// redirect console output to parent process;
// must be before any calls to Console.WriteLine()
AttachConsole(ATTACH_PARENT_PROCESS);
int argCount = args == null ? 0 : args.Length;
Console.WriteLine( "\nNo of arguments: {0}", argCount );
for (int i = 0; i < argCount; i++)
{
Console.WriteLine( " {0}", args[i] );
}
if (args.Length==0)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Regards,
raaj