Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

c# - How do I write to command line from a WPF application?

Hi I know how to write to console but if I write to console in my program and call my program from the command line it won't display anything.

How do I make it so that when I say Console.WriteLine or Console.Out.Writeline ir prints to the command prompt from which it was called and not somewhere else?

Once again I know how to do Console.WriteLine so it's not that :-p unless I'm doing it wrong.

From what I can tell it's probably something to do with Console.SetOut(TextWriter t)

this is a WPF application and I need it to post its data to the command line while still retaining the GUI at startup. I've triple checked and my code hits the print lines, I can actually see the lines being printed to the Visual Studio output window, it just won't display in the command line when I run it manually without VS.

If possible I need to conditionally have the console display. ie if run from command line (or even with command arguments), display or post to the prompt, otherwise do not.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is actually trivial:

public void WriteToConsole(string message)
{
  AttachConsole(-1);
  Console.WriteLine(message);
}
[DllImport("Kernel32.dll")]
public static extern bool AttachConsole(int processId);

This method will write your message to the console if your program was started from the command line, otherwise it will do nothing.

If you want to use an alternative output mechanism when you weren't started from the command line you can do it this way:

public void WriteToConsole(string message)
{
  _connected = _connected || AttachConsole(-1);
  if(_connected)
    Console.WriteLine("Hello");
  else
    ... other way to output message ...
}
bool _connected;
[DllImport("Kernel32.dll")]
public static extern bool AttachConsole(int processId);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...