No console output when using AllocConsole and target architecture x86

前端 未结 5 1317
-上瘾入骨i
-上瘾入骨i 2020-11-27 17:05

I have a WinForms project, and if the user want\'s a debug console, I allocate a console with AllocConsole().

All console output works normally with the

5条回答
  •  粉色の甜心
    2020-11-27 17:35

    Following worked for me in vs 2015, none worked from other answers:

    Source: https://social.msdn.microsoft.com/profile/dmitri567/?ws=usercard-mini

    using System;   
    using System.Windows.Forms;   
    using System.Text;   
    using System.IO;   
    using System.Runtime.InteropServices;   
    using Microsoft.Win32.SafeHandles;   
    
    namespace WindowsApplication   
    {   
        static class Program   
        {   
            [DllImport("kernel32.dll",   
                EntryPoint = "GetStdHandle",   
                SetLastError = true,   
                CharSet = CharSet.Auto,   
                CallingConvention = CallingConvention.StdCall)]   
            private static extern IntPtr GetStdHandle(int nStdHandle);   
            [DllImport("kernel32.dll",   
                EntryPoint = "AllocConsole",   
                SetLastError = true,   
                CharSet = CharSet.Auto,   
                CallingConvention = CallingConvention.StdCall)]   
            private static extern int AllocConsole();   
            private const int STD_OUTPUT_HANDLE = -11;   
            private const int MY_CODE_PAGE = 437;   
    
            static void Main(string[] args)   
            {   
                Console.WriteLine("This text you can see in debug output window.");   
    
                AllocConsole();   
                IntPtr stdHandle=GetStdHandle(STD_OUTPUT_HANDLE);   
                SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);   
                FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);   
                Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);   
                StreamWriter standardOutput = new StreamWriter(fileStream, encoding);   
                standardOutput.AutoFlush = true;   
                Console.SetOut(standardOutput);   
    
                Console.WriteLine("This text you can see in console window.");   
    
                MessageBox.Show("Now I'm happy!");   
            }   
        }   
    }  
    

提交回复
热议问题