0

While working on a project of mine. I found the need to have the normal console aplication for changing numbers and putting them out. I found out a post that made that pretty easy, but it doesn't output anything. it opens the console aplication and the name changes, but there is no output.

This is what i use to open it

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

    private void UseConsole(object sender)
    {
        AllocConsole();
        Console.Title = "Output";
        Console.Write("hello world");
    }

If you know what might help to get an output. that would be great Thanks already

Dan

1 Answers1

-1

I had the same problem when trying to create a console with my XNA/FNA application. All the common solutions found didn't worked: the written console lines were printed into the "Output" window of Visual Studio (Community), but when the application was started by executing the game directly (outside of Visual Studio), the console window remained empty. The following answer on a similar question worked for me: https://stackoverflow.com/a/34170767 by https://stackoverflow.com/users/1087922/zunair

The copied code:

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!");   
        }   
    }   
}
Community
  • 1
  • 1