Pregunta

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

¿Fue útil?

Solución

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.

Otros consejos

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);

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);
        }
    }
    

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.

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top