如何将控制台输出添加到 Windows wpf 应用程序 C#

发布于 2024-12-06 17:30:15 字数 113 浏览 0 评论 0原文

我想添加一个额外的控制台窗口来记录来自我的 wpf 应用程序的实时信息。 有什么想法吗?

巴约

回答: 项目属性中的控制台应用程序对我有用。 谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

記憶穿過時間隧道 2024-12-13 17:30:15

您可以调用 AttachConsole WIN API 函数,然后使用 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);

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);
李不 2024-12-13 17:30:15

不要这样做。

查看 log4netNLog 用于将日志输出到文件中。通过这些框架的正确配置,您可以获得更多的功能(不同的日志级别、自动时间戳、每个记录行前面的自动类名称)

并且当您使用它时,您可能还想实现自己的外观,从代码的其余部分隐藏使用的日志记录框架。这将使您可以在需要时轻松更改日志记录框架。


如果您希望程序同时具有控制台和 GUI 窗口,则可以通过将项目编译为控制台应用程序 (csc /target:exe) 来实现此行为。但要注意:这肯定会导致可用性较差,因为没有用户会期望您的应用程序同时具有控制台和 GUI 窗口。

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.

忘年祭陌 2024-12-13 17:30:15

谢谢你上面的想法。以下是将控制台窗口添加到 WPF 应用程序所需的所有步骤。我们修改了 WPF 测试应用程序,以便可以在夜间测试过程中从命令行调用它。唯一的问题是,当应用程序从控制台运行时,在调用 FreeConsole() 并且应用程序退出后,命令提示符不会立即写入控制台窗口。 FreeConsole() 函数似乎缺少对类似 Flush() 的函数的调用,以强制将命令提示符写入控制台窗口。我的推理是,控制台窗口向上/向下箭头历史记录可用,并且控制台接受另一个命令,但是当下一个应用程序运行并写入控制台窗口时,将写入丢失的命令提示符。

  1. 在项目属性“应用程序”选项卡中,保留“输出类型”=“Windows 应用程序”。
  2. 右键单击 App.xaml 并选择 Properties
  3. 设置 Build Action = Page
  4. 打开 App.xaml.cs 并修改 App 类,如下所示。

    公共部分类App:应用程序
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        静态 extern bool AttachConsole(uint dwProcessId);
    
        [DllImport("kernel32.dll", SetLastError = true)]
        静态 extern bool FreeConsole();
    
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        内部静态 extern int GetConsoleTitle(System.Text.StringBuilder sbTitle, int 容量);
    
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        内部静态外部布尔SetConsoleTitle(字符串sTitle);
    
        [STA线程]
        公共静态 int Main(字符串[] args)
        {
            布尔值 h​​asExceptionOccured = false;
    
            System.Text.StringBuilder sbTitle = new System.Text.StringBuilder();
    
            尝试
            {
                // 如果用户不提供任何参数,则假定他们希望在 GUI 模式下运行。
                if (0 == args.Length)
                {
                    var application = new App();
                    application.InitializeComponent();
                    应用程序.Run();
                }
                别的
                {
                    const uint ATTACH_PARENT_PROCESS = 0x0ffffffff; // 如果未指定进程 ID,则使用默认值。
    
                    // 连接到启动该应用程序的控制台。
                    AttachConsole(ATTACH_PARENT_PROCESS);
    
                    // 获取控制台窗口的当前标题。
                    GetConsoleTitle(sbTitle, 64);
    
                    // 将控制台标题设置为该应用程序的名称和版本。
                    SetConsoleTitle(Global.thisProgramsName + " - v" + Global.thisProductVersion);
    
                    // 创建控制台类的实例并调用它的 Run() 方法。
                    var mainConsole = new ReportTester.MainConsole();
                    mainConsole.Run(args);                   
                }
            }
            catch (System.Exception 前)
            {
                System.Console.WriteLine(例如.Message);
                System.Console.WriteLine(例如StackTrace);
                if (null != ex.InnerException)
                {
                    System.Console.WriteLine(例如.InnerException.Message);
                    System.Console.WriteLine(例如.InnerException.StackTrace);
                }
                有异常发生 = true;
            }
            最后
            {
                // 由于释放时控制台不会显示提示,所以我们这里提供一个。
                System.Console.Write(“>”);
    
                // 恢复控制台标题。
                SetConsoleTitle(sbTitle.ToString());
    
                // 释放控制台。
                自由控制台();
            }
    
            return (hasExceptionOccured ? 1 : 0);
        }
    }
    

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);
        }
    }
    
咋地 2024-12-13 17:30:15

要求不明确。听起来好像唯一真正的要求是能够重定向标准输出;似乎不需要控制台窗口。

在空白(新)WPF 应用程序中,将以下内容添加到 Loaded 事件或其他事件中:

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

然后从命令提示符执行程序并将标准输出重定向到文件。输出将在文件中。标准输入可以以相应的方式重定向。

这对于我们无法控制的标准 IO 要求的情况非常有用。我们可以将 GUI 窗口与标准 IO 结合起来。

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.

删除会话 2024-12-13 17:30:15

如果您希望程序同时具有控制台和 GUI 窗口,可以通过将项目编译为控制台应用程序来实现。

只需转到项目属性并将输出类型更改为控制台应用程序

现在,当您运行时,您将同时获得 WPF 窗口和控制台窗口。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文