Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to command line if application is executed from cmd

Tags:

c#

cmd

console

I searched the web and Stackoverflow, I didn't find anything. I am sorry if this question already exists.

If my C# application is called through the cmd for example:

C:\System32\MyConsoleApplication -parmOne -paramTwo ...

Is there a way to write into the cmd (for example to giving progressinformation?)

Edit: Cause I use a Consoleapplication the solution ist Console.WriteLine It doesnt worked for me cause my application requires adminrights (trough a Manifestfile) and was called with normal userrights. In this case the UAC asks for rights and opens a new Cmd with the application.

like image 364
BudBrot Avatar asked Dec 08 '22 13:12

BudBrot


1 Answers

better solution : http://www.nerdyhearn.com/blog/157/

here is the code of the site:

[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;

[STAThread]
static void Main(string[] args)
{
  // Enable visual elements just like always
  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);

  // Attach to the parent process via AttachConsole SDK call
  AttachConsole(ATTACH_PARENT_PROCESS);   // <-- important point here
  Console.WriteLine("This is from the main program");

  Application.Run(new Form1());
}

You can use the AttachConsole call at your will in the special conditions you need. This is much better and flexible and does not require you to change your application manifest. if its a win32 app, wll good for your app. if its launched from a cmd then the output will appear as excpected.

My opinion: this is just some useless microsoft complication of some concepts that are so pure and natural in the Unix world. If your application is launched from a visual launcher (icon, nautilus..) then the output is lost. You can launch your app from a console and its gets in the console. you can redirect the output if you need, it all imbricates logically and its powerful. With microsoft... its bloated and gets in the way of everybody.

like image 152
v.oddou Avatar answered Dec 11 '22 12:12

v.oddou