c# - 如何拥有程序执行时间的控制台?

标签 c# winapi user-interface console

我正在尝试编写一个程序,它可以在控制台或 GUI 模式下运行,具体取决于执行参数。我设法编写了以下示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace wfSketchbook
{
    static class Program
    {
        [DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool AttachConsole(int processId);

        [DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool AllocConsole();

        [DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool FreeConsole();

        private const int ATTACH_PARENT_PROCESS = -1;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                if (!AttachConsole(ATTACH_PARENT_PROCESS))
                    AllocConsole();
                Console.WriteLine("Welcome to console!");
                Console.ReadKey();
                FreeConsole();
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
}

它通常可以工作,但是当从系统命令行调用程序时,cmd 似乎不知道,该程序在控制台模式下工作并立即退出:

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>wfSketchbook.exe test

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>Welcome to console!

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>

我宁愿期待以下输出:

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>wfSketchbook.exe test

Welcome to console!

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>

我该如何解决这个问题?

最佳答案

对此没有理想的解决方案。如果 Cmd.exe 可以看到 .exe 是控制台模式应用程序,它只会自动等待程序完成。您的应用程序不会出现这种情况。一种解决方法是让它等待:

start /wait yourapp.exe [arguments]

另一个是始终使用 AllocConsole()。它的副作用是它创建了第二个控制台窗口。将应用程序类型更改为 Console 然后调用 FreeConsole() 也不理想,窗口的闪烁非常明显。选择你的毒药。

关于c# - 如何拥有程序执行时间的控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7058491/

相关文章:

winapi - Windows 中的所有控件都称为通用控件吗?

python - 单个选项卡中的多个框架 ttk.Notebook

java - Android 自定义微调器,带图像选择功能

c++ - Qt:实现 "oscilloscope-like"实时绘图的最佳方式

c++ - win32 C++ 打印 PRINTDLGEX 未声明?

c# - XSLT 的输出参数

c# - 无效的列名 C#

C# Selenium ChromeDriver - 如何抑制打印预览,pdf

c# - 获取进程的所有 DLLS

c# - 如何知道用户是否正在使用多个显示器