在窗口化应用程序中写入命令行

Writing to the command line in a windowed app(在窗口化应用程序中写入命令行)

本文介绍了在窗口化应用程序中写入命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的基于 WinForm 的 C# 也与命令行配合,但我很难让它发挥得很好.例如,我有这样的代码:

I'm trying to get my WinForm based C# to cooperate with the commandline too, but I'm having difficulty getting it to play nice. For example, I have this code:

    [STAThread]
    static void Main(string[] args) {
        foreach (string s in args) {
            System.Windows.Forms.MessageBox.Show(s);
            Console.WriteLine("String: " + s);
        }

        Mutex appSingleton = new System.Threading.Mutex(false, "WinSyncSingalInstanceMutx");
        if (appSingleton.WaitOne(0, false)) {
            try {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                //start logger
                Logger.singleton.makeOpen(true);
                Application.Run(new MainForm(false));
            } catch (Exception) {
            } finally {
                appSingleton.Close();
                Logger.singleton.makeOpen(false); 
            }
        } else {
            System.Windows.Forms.MessageBox.Show("Sorry, only one instance of WinSync can be ran at once.");
        }
    }
}

它应该使用 Console.WriteLine 写入控制台,但我什么也没看到,只有 MessageBox 出现.

It should write to the console with the Console.WriteLine, but I see nothing, only the MessageBox shows up.

我做错了什么?

推荐答案

尝试 AttachConsole(-1) 重定向 Console.Out,对我有用:

Try AttachConsole(-1) to redirect Console.Out, worked for me:

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

namespace PEFixer
{
    static class Program
    {
        [DllImport("kernel32.dll")]
        private static extern bool AttachConsole(int dwProcessId);

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static int Main(string[] args)
        {
            if (args.Length > 0)
            {
                AttachConsole(-1);
                return Form1.doTransformCmdLine(args);
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            return 0;
        }
    }
}

这篇关于在窗口化应用程序中写入命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在窗口化应用程序中写入命令行