C# debug log console app

我的未来我决定 提交于 2019-12-11 17:53:38

问题


I am trying to create a console window for debugging in C#.

For example, consider the following scenario:

I have a forms app and I want to log events to a console window in real time.
When an event is triggered the forms app should send data to be printed to the console app so that I can see when the event is triggered and data about the specific event.
When I input a specific command in the console app, it sends the command to the forms app and triggers the event.

Because it is for debugging, the console should be a separate app so that if the main app dies, the console window won't.

If I do this right I assume I should be able to get the console app working with programs such as Console2/Conemu.

Does anyone know the correct technique to achieve this?


回答1:


Thee ways, I think, depending how do you want to initialize communication between your processes. I believe, named pipes - is the best choice. But as you wish...

1) You may "create" your console with following command

ConEmuC.exe /ATTACH /ROOT "<Full path to your console\part.exe>" <Arguments console part>
or
ConEmu.exe /cmd "<Full path to your console\part.exe>" <Arguments console part>

2) "Attach" created console from normally started console part application. Read here. The idea is to run following command in the free, just created console.

ConEmuC.exe /AUTOATTACH

3) At last, you may try "Default Terminal" feature. Described here.




回答2:


Update (because I missunderstood the question):

You can use the process class to start a process from your Forms application and just redirect the output stream.

You would execute it like this:

ExecuteProcess(@"ConsoleApp.exe", "some arguments here");

// and now you can access the received data from the process from the
// receivedData variable.

Code:

/// <summary>
/// Contains the received data.
/// </summary>
private string receivedData = string.Empty;

/// <summary>
/// Starts a process, passes some arguments to it and retrieves the output written.
/// </summary>
/// <param name="filename">The filename of the executable to be started.</param>
/// <param name="arguments">The arguments to be passed to the executable.</param>
private void ExecuteProcess(string filename, string arguments)
{
    Process p = new Process();

    // Define the startinfo parameters like redirecting the output.
    p.StartInfo = new ProcessStartInfo(filename, arguments);
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.UseShellExecute = false;
    p.OutputDataReceived += this.OutputDataReceived;

    // Start the process and also start reading received output.
    p.Start();
    p.BeginOutputReadLine();

    // Wait until the process exits.
    p.WaitForExit();
}

/// <summary>
/// Is called every time output data has been received.
/// </summary>
/// <param name="sender">The sender of this callback method.</param>
/// <param name="e">The DataReceivedEventArgs that contain the received data.</param>
private void OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    this.receivedData += e.Data;
}

Old Answer:

Basically you will get access to all specified command line arguments by accessing the "args" parameter in the main method. The little example prints all specified command line arguments (they are spereated with a space-character between them) to the console and waits for a key to be pressed before exiting.

Example:

/// <summary>
/// Represents our program class which contains the entry point of our application.
/// </summary>
public class Program
{
    /// <summary>
    /// Represents the entry point of our application.
    /// </summary>
    /// <param name="args">Possibly spcified command line arguments.</param>
    public static void Main(string[] args)
    {
        // Print the number of arguments specified to the console.
        Console.WriteLine("There ha{0} been {1} command line argument{2} specified.",
                          (args.Length > 1 ? "ve" : "s"), 
                          args.Length,
                          (args.Length > 1 ? "s" : string.Empty));

        // Iterate trough all specified command line arguments
        // and print them to the console.
        for (int i = 0; i < args.Length; i++)
        {
            Console.WriteLine("Argument at index {0} is: {1}", i, args[i]);
        }

        // Wait for any key before exiting.
        Console.ReadKey();
    }
}

Don't be confused by the arguments in the first WriteLine statement, I just wanted to print singular and plural correctly.

You can specify the command line argument either by passing them on the command line:

Example: Your.exe argument1 argument2 argument3

Or in the IDE by using the properties of the project (right click on your project in the solution explorer -> Properties -> Debug -> Command line arguments)

I hope I understood your question correctly and this helps ;-)




回答3:


Once, I wanted to log into a console but the application was NOT a console app. The solution I found was to allocate a new console to the calling process

[DllImport("kernel32.dll")]
private static extern bool AllocConsole();

Later in the App.xaml.cs, I allocate the console

if (arguments.HookConsole)
{
    //Hook the console to the application to have logging features
    AllocConsole();
}

Unfortunately, when the main application stops, the console stops too...



来源:https://stackoverflow.com/questions/19599107/c-sharp-debug-log-console-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!