显示WinForms程序的控制台窗口



我有一个WinForms程序。如果用户从命令行启动它并传递一个无效参数,我如何在控制台窗口中显示错误信息?

下面是一个示例,如果坏参数被传递到winform应用程序,如何向命令行显示消息:

static class Program
{
    [DllImport("kernel32.dll")]
    static extern bool AttachConsole(int dwProcessId);
    private const int ATTACH_PARENT_PROCESS = -1;
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        //if parameter -window is passed - opens main form, else displays Bad params message
        if(args[0] == "-window")
            Application.Run(new main());
        else
        {
            //Attach console process
            AttachConsole(ATTACH_PARENT_PROCESS);
            Console.WriteLine("Bad params");
        }
    }
}

参考:http://www.csharp411.com/console-output-from-winforms-application/

您可以使用Console.WriteLine(message)方法输出信息。

您的WinForms应用程序可能会弹出一个显示错误的弹出窗口,如消息框。

如果应用程序作为批处理文件的一部分在无人参与模式下运行,则可以写入事件日志或应用程序创建的自定义日志文件。

如果您的批处理命令将输出重定向到一个文件,例如…,那么告诉您使用Console.WriteLine的其他答案也很好

myApp.exe>>errors.txt

这会将控制台附加到error.txt文件中。。。

最新更新