Reputation: 5264
I have written the application which works in console as well as a user interface. Now when executing the application from a console, I want to show the message in the currently opened console.
static class Program
{
[DllImport("kernel32.dll",
EntryPoint = "GetStdHandle",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll",
EntryPoint = "AllocConsole",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int AllocConsole();
private const int STD_OUTPUT_HANDLE = -11;
private const int MY_CODE_PAGE = 437;
[STAThread]
static void Main(string[] Args)
{
if (Args[0] != "")
{
//AllocConsole();
commandlineTool(Args[0]);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form2());
}
static void commandlineTool(string filename)
{
//all coding here
AllocConsole();
IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine("File has been generated.");
Console.ReadLine();
}
Actually AllocConsole() allocate new console for the process.
But from this a new console opens and shows the message but I want to show the message in the same console.
Upvotes: 1
Views: 2249
Reputation: 6447
Method A (preferred, easy):
You can make the application a console application, and release the console if started in GUI mode using FreeConsole
. This IMO is the best solution. The only drawback is that the console window will be shown very briefly when starting the application.
Method B (use when necessary):
You can try to attach to the parent process' console using AttachConsole(ATTACH_PARENT_PROCESS)
. If the parent process doesn't have a console this will fail, in which case you'd have to go back to using AllocConsole.
Also if the System.Console
class has already been initialized when you try to attach/allocate the console, you'll have to re-wire the in/out/error streams like this:
StreamWriter stdOut = new StreamWriter(Console.OpenStandardOutput());
stdOut.AutoFlush = true;
Console.SetOut(stdOut);
StreamWriter stdErr = new StreamWriter(Console.OpenStandardError());
stdErr.AutoFlush = true;
Console.SetError(stdErr);
StreamReader stdIn = new StreamReader(Console.OpenStandardInput());
Console.SetIn(stdIn);
Otherwise you'll have no output.
Upvotes: 1