「Androidは電気羊の夢を見るか」を読みたい管理者のブログ

仕事などでの色々な発見を記事にしてます。不定期更新。

FormApplicationでConsole出力できたよー\(^o^)/

FormApplicationでConsoleOutがやりたいと思ったことはないでしょうか。

プロジェクトの作成でFormApplicationを選択するとConsole領域が用意されないのですね。
そこで出番となるのが

AllocConsole()

関数
ただこれはWindowsAPIなため、C#から呼び出すにはひと工夫必要です。

そう、DllImportするのです。

[DllImport("kernel32")]
static extern bool AllocConsole();

こんな感じに。

System.Runtime.InteropServiceもusingに入れることを忘れないようにしましょう!

で、出来たサンプルが

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CreateConsole();
            Console.WriteLine("test2");

        }
        public static void CreateConsole()
        {
            AllocConsole();

            // stdout's handle seems to always be equal to 7
            IntPtr defaultStdout = new IntPtr(7);
            IntPtr currentStdout = GetStdHandle(StdOutputHandle);

            if (currentStdout != defaultStdout)
                // reset stdout
                SetStdHandle(StdOutputHandle, defaultStdout);

            // reopen stdout
            TextWriter writer = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };
            Console.SetOut(writer);
        }

        // P/Invoke required:
        private const UInt32 StdOutputHandle = 0xFFFFFFF5;
        [DllImport("kernel32.dll")]
        private static extern IntPtr GetStdHandle(UInt32 nStdHandle);
        [DllImport("kernel32.dll")]
        private static extern void SetStdHandle(UInt32 nStdHandle, IntPtr handle);
        [DllImport("kernel32")]
        static extern bool AllocConsole();
    }

出力結果が
f:id:bignight:20150114191906p:plain
こんな感じ。

C言語でやりたい場合

	hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
	//標準出力に書き込み
	WriteFile(hConsoleOut, pWriteBuf, dwBufSize, &dwBuf, NULL);

詳しくはここを見てくれたまえ↓
WriteFile 関数


Thanks:

c# - No console output when using AllocConsole and target architecture x86 - Stack Overflow