9

i would like to add an additional console window to log realtine info from my wpf application. Any idea??

Bayo

answer: console application in the project properties works for me. thank's

Bayo Alen
  • 341
  • 1
  • 6
  • 13
  • By "additional", do you mean that you've already used the built-in console? Windows only allows a process to be attached to a single console, so if you want more than one, your options are (1) use a helper process or (2) make a GUI window that looks like a console. – Ben Voigt Sep 26 '11 at 17:35
  • 1
    If something works for you, *don't* edit your question. Instead mark the answer as accepted and *maybe* upvote it – yas4891 Sep 26 '11 at 17:54
  • @yas4891 No one actually added that answer, it was the answer I was looking for myself. He should have posted the answer then marked it as an answer. – Daniel Armstrong Apr 26 '19 at 02:35

5 Answers5

5

Don't do it.

Take a look at log4net or NLog for log output into a file. With the right configuration of those frameworks you get a lot more power (different log levels, automatic timestamps, automatic class names in front of every logged line)

And while you are at it, you might also want to implement a facade of your own, to hide the used logging framework from the rest of your code. This would allow you to easily change the logging framework, if and when the need arises.


If you want to have both a console and a GUI window for your program, you could implement this behaviour by compiling the project as console application (csc /target:exe). But beware: This most certainly leads to bad usability, because no user would expect your app to have both a console and a GUI window.

yas4891
  • 4,774
  • 3
  • 34
  • 55
  • 1
    Would you at least have the courtesy to explain that downvote? – yas4891 Sep 26 '11 at 17:28
  • +1 We use NLog at work, it's very useful, though depending on the situation for the OP, may not be the best tool (which obv we can't extrapolate) – Psytronic Sep 26 '11 at 18:02
  • 1
    compiling the project as console application works for me Thanks alot bros – Bayo Alen Sep 28 '11 at 12:35
  • .Net seems to support it. See my answer. – Sam Hobbs Jan 09 '19 at 03:48
  • 4
    Answers like this are beyond stupid. Nowhere in the question does he ask how to log to a file, this answer is completely irrelevant from the question. You really should remove your "Don't do it" answer, don't get me wrong log4net is awesome (though I prefer Serilog since it supports structured logging) but it has nothing to do with the question here. – Daniel Armstrong Apr 26 '19 at 02:39
5

You could call AttachConsole WIN API function and then call this function using PInvoke:

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AttachConsole(uint dwProcessId);

const uint ATTACH_PARENT_PROCESS = 0x0ffffffff;  // default value if not specifing a process ID

// Somewhere in main method
AttachConsole(ATTACH_PARENT_PROCESS);
Sergey Teplyakov
  • 11,477
  • 34
  • 49
  • I know this isn't the best answer for this question, but I stumbled upon this when I was trying to have my WPF application work both from the command line and from a regular GUI. This was the trick I was looking for. Now when a user puts the command line switch in I can output information to the console window and when it is run from the GUI it uses the regular Log4Net logging. Thanks! – Mike G May 23 '12 at 18:26
1

Thank you for the ideas above. Here are all the steps necessary to add a console window to a WPF application. We modified our WPF test application so that it could be called from the command line during the nightly test process. The only glitch is when the application runs from the console, the command prompt is not immediately written to the console window after FreeConsole() is called and our application exits. The FreeConsole() function appears to be missing a call to a Flush() like function to force write the command prompt to the console window. My reasoning is that the console window up/down arrow history is available and the console accepts another command but when the next application runs and writes to the console window the missing command prompt is written with it.

  1. In the project properties Application tab, leave the Output Type = Windows Application.
  2. Right click on App.xaml and choose Properties
  3. Set the Build Action = Page
  4. Open App.xaml.cs and modify the App class like below.

    public partial class App : Application
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AttachConsole(uint dwProcessId);
    
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool FreeConsole();
    
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern int GetConsoleTitle(System.Text.StringBuilder sbTitle, int capacity);
    
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool SetConsoleTitle(string sTitle);
    
        [STAThread]
        public static int Main(string[] args)
        {
            Boolean hasExceptionOccured = false;
    
            System.Text.StringBuilder sbTitle = new System.Text.StringBuilder();
    
            try
            {
                // If the user does not provide any parameters assume they want to run in GUI mode.
                if (0 == args.Length)
                {
                    var application = new App();
                    application.InitializeComponent();
                    application.Run();
                }
                else
                {
                    const uint ATTACH_PARENT_PROCESS = 0x0ffffffff;  // Default value if not specifying a process ID.
    
                    // Attach to the console which launched this application.
                    AttachConsole(ATTACH_PARENT_PROCESS);
    
                    // Get the current title of the console window.
                    GetConsoleTitle(sbTitle, 64);
    
                    // Set the console title to the name and version of this application.
                    SetConsoleTitle(Global.thisProgramsName + " - v" + Global.thisProductVersion);
    
                    // Create a instance of your console class and call it’s Run() method.
                    var mainConsole = new ReportTester.MainConsole();
                    mainConsole.Run(args);                   
                }
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Console.WriteLine(ex.StackTrace);
                if (null != ex.InnerException)
                {
                    System.Console.WriteLine(ex.InnerException.Message);
                    System.Console.WriteLine(ex.InnerException.StackTrace);
                }
                hasExceptionOccured = true;
            }
            finally
            {
                // Since the console does not display the prompt when freed, we will provide one here.
                System.Console.Write(">");
    
                // Restore the console title.
                SetConsoleTitle(sbTitle.ToString());
    
                // Free the console.
                FreeConsole();
            }
    
            return (hasExceptionOccured ? 1 : 0);
        }
    }
    
Jay
  • 11
  • 1
  • I don't see how this is supposed to work.What does ReportTester.MainConsole look like? Where does the Run method come from? – dutop Jul 30 '19 at 05:59
1

The requirements are not clear. It sounds as if the only real requirement is to be able to redirect the standard output; there seems to be no need for the console window.

In a blank (new) WPF application add the following to the Loaded event or whatever:

Stream StdoutStream = OpenStandardOutput();
StreamWriter Stdout = new StreamWriter(StdoutStream);
Stdout.WriteLine("Line one");
Stdout.WriteLine("Line two");
Stdout.WriteLine("Hello");
Stdout.WriteLine("Bye");
Stdout.Flush();
Stdout.Close();

Then execute the program from a command prompt and redirect standard output to a file. The output will be in the file. Standard input can be redirected in a corresponding manner.

This can be very useful for situations where standard IO is a requirement that we have no control of. We can have a GUI window combined with standard IO.

Sam Hobbs
  • 2,594
  • 3
  • 21
  • 32
1

If you want to have both a console and a GUI window for your program, you can implement this by compiling the project as a console application.

Just go to your project properties and change the output type to console application

Now when you run you will get both the WPF window and a console window.

Daniel Armstrong
  • 829
  • 9
  • 22