Search code examples
c#consolewiresharkmaui

Write to the console in .net MAUI


Good day everyone,

i have a problem with MAUI. I am running a MAUI project that acts as a UI to configurate a capture device that is used to capture network traffic and display this in Wireshark using a custom extcap.

The two programs work in tandem, as Wireshark starts the MAUI program by calling it on a command line with parameters.

The problem is, Wireshark is communicating by reading of and writing to a console. This means I need to write from the MAUI application to the console it was started from by Wireshark.

I tried both Console.WriteLine as well as a Trace.Listener without success.

 string interfaceString = "interface {value=" + capturer.Name + "}{display=" + capturer.Name + " Capture Interface}";
 Console.WriteLine(interfaceString);

 Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
 Trace.WriteLine(interfaceString);

My question now is, is there a way to write to the console, or is it in fact impossible to get MAUI to communicate via the console. It would be sufficient to me if a solution for Windows exists.


Solution

  • To finish this up for anyone who has the same problem: As it is simply not possible to access the console MAUI runs from, it is the best idea to use a small middleware program.

    This middleware is called by wireshark and starts the MAUI UI in a new thread. In MAUI itself, we can then reroute the output to the middleware that catches it and writes it back to Wireshark.

    Middleware:

    Process p = new Process();
    try
    {
        p.StartInfo.FileName = pathToEXE;
        p.StartInfo.Arguments = $"im an arg";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.ErrorDialog = true;
        p.StartInfo.WorkingDirectory = Path.GetDirectoryName(pathToEXE);
        p.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
        p.Start();
    }
    catch (Exception ex)
    {
       Console.WriteLine("Could not start MAUI: " + ex);
    }
        
    while (!p.HasExited)
    {
        Console.Out.Write(p.StandardOutput.ReadToEnd());
    }
    Console.WriteLine(p.StandardOutput.ReadToEnd());
    

    MAUI Windows App.xaml.xs

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool AllocConsole();
    
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool AttachConsole(int pid);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool FreeConsole();
    
    private static extern bool FreeConsole();
    
    bool parentConsole = AttachConsole(Int32.Parse(processID)
    

    The process id must be transfered to MAUI as a command line argument.