none
Console Exception on Windows 8 RRS feed

  • Question

  • Hello

    I have a simple WinForms application, there are two buttons, one of them runs console and the other closes it.
    Below find enclosed the following code.

            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                AllocConsole();
                Console.WriteLine("Start");
            }     
    
            private void button2_Click(object sender, EventArgs e)
            {
                FreeConsole(); 
            }
            
            [System.Runtime.InteropServices.DllImport("kernel32.dll")]
            private static extern bool AllocConsole();
    
            [System.Runtime.InteropServices.DllImport("kernel32.dll")]
            private static extern bool FreeConsole();

    The problem appears when I want to run and close the console several times, that works on  Windows Xp and Windows 7, but  on Windows 8 after I close the console for the first time and run it again I get an  exception IOException in line Console.WriteLine ("Start");

    Any idea?
    Thanks in advance.

    Wednesday, March 20, 2013 4:26 PM

Answers

  • It seems that Console class does not always work in case of atypical usage of console. Try hiding the console window instead of destroying:

    private void button1_Click(object sender, EventArgs e)
    {
        IntPtr hw = GetConsoleWindow();
        if (hw == IntPtr.Zero) AllocConsole();
        Console.Clear();
        ShowWindow(hw, 8);
        Console.WriteLine("Start");
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        IntPtr hw = GetConsoleWindow();
        if (hw != IntPtr.Zero) ShowWindow(hw, 0);
    }
    
    [DllImport("kernel32.dll")]
    private static extern IntPtr GetConsoleWindow();
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);


    • Edited by Viorel_MVP Saturday, March 23, 2013 3:53 PM
    • Marked as answer by Kriss_p Sunday, March 24, 2013 6:13 PM
    Saturday, March 23, 2013 3:53 PM

All replies

  • Hi Kriss,

    Welcome to the MSDN Forum.

    It seems that the AllocConsole didn't work well, please use an integer to get the return value and try to figure it out. If you need further assitance, please post the error code here, we will check it.

    Thank you.

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, March 21, 2013 8:44 AM
    Moderator
  • Hi Mike
    Below find enclosed the details of exception

    System.IO.IOException occurred
      HResult=-2147024890
      Message=Nieprawidłowe dojście. (The handle is invalid)

      Source=mscorlib
      StackTrace:
           w System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
           w System.Console.Clear()
           w SGF.Helper.AsyncConsole.MainLoop() w d:\TestProject 1.1\SGF\SGF\Helper\AsyncConsole.cs:wiersz 132
      InnerException:

    I found a similar topic in this forum but I dont know if it is the same case.
    http://social.msdn.microsoft.com/Forums/en-US/clr/thread/e025f6de-8b79-40c1-9896-f8a852cd6b49/

    Thursday, March 21, 2013 11:49 AM
  • Try this workaround:

    private void button2_Click(object sender, EventArgs e)
    {
        Console.OutputEncoding = Console.OutputEncoding;
        FreeConsole();
    }

    Friday, March 22, 2013 6:25 AM
  • Thank you for the tip Viorel

    Interesting, this code (Console.OutputEncoding = Console.OutputEncoding) helped but only with a simple example. When I use other methods or properties, the problem continues on the second run of the console.

    For example:
    Console.Clear() throws exception:

    System.IO.IOException was unhandled
      Message=Nieprawidłowe dojście. (The handle is invalid)
    
      Source=mscorlib
      StackTrace:
           w System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
           w System.IO.__Error.WinIOError()
           w System.Console.Clear()
           w WinFormConsoleThread.Form1.button1_Click(Object sender, EventArgs e) w c:\Projekty Csharp\Test\WinFormConsoleThread\WinFormConsoleThread\Form1.cs:wiersz 44
           w System.Windows.Forms.Control.OnClick(EventArgs e)
           w System.Windows.Forms.Button.OnClick(EventArgs e)
           w System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           w System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           w System.Windows.Forms.Control.WndProc(Message& m)
           w System.Windows.Forms.ButtonBase.WndProc(Message& m)
           w System.Windows.Forms.Button.WndProc(Message& m)
           w System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           w System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           w System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           w System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           w System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           w System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           w System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           w System.Windows.Forms.Application.Run(Form mainForm)
           w WinFormConsoleThread.Program.Main() w c:\Projekty Csharp\Test\WinFormConsoleThread\WinFormConsoleThread\Program.cs:wiersz 18
           w System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           w System.Threading.ThreadHelper.ThreadStart()
      InnerException: 
    and Console.ReadKey() sometimes throws excpetion:
    System.InvalidOperationException was unhandled
      Message=Cannot read keys when either application does not have a console or when console input has been redirected from a file
      Source=mscorlib
      StackTrace:
           w System.Console.ReadKey(Boolean intercept)
           w System.Console.ReadKey()
           w WinFormConsoleThread.Form1.button1_Click(Object sender, EventArgs e) w c:\Projekty Csharp\Test\WinFormConsoleThread\WinFormConsoleThread\Form1.cs:wiersz 44
           w System.Windows.Forms.Control.OnClick(EventArgs e)
           w System.Windows.Forms.Button.OnClick(EventArgs e)
           w System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           w System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           w System.Windows.Forms.Control.WndProc(Message& m)
           w System.Windows.Forms.ButtonBase.WndProc(Message& m)
           w System.Windows.Forms.Button.WndProc(Message& m)
           w System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           w System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           w System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           w System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           w System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           w System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           w System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           w System.Windows.Forms.Application.Run(Form mainForm)
           w WinFormConsoleThread.Program.Main() w c:\Projekty Csharp\Test\WinFormConsoleThread\WinFormConsoleThread\Program.cs:wiersz 18
           w System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           w System.Threading.ThreadHelper.ThreadStart()
      InnerException:

    I noticed that after the release of the console (FreeConsole) and starting again (AllocConsole) on Windows 8 some properties do not initialize properly:

    CursorSize, CursorVisible, KeyAvailable, TreatControlCAsInput

    There are exceptions in these properties. On Windows 7 after re-initializing AllocConsole all properties are ok.


    Friday, March 22, 2013 10:02 PM
  • It seems that Console class does not always work in case of atypical usage of console. Try hiding the console window instead of destroying:

    private void button1_Click(object sender, EventArgs e)
    {
        IntPtr hw = GetConsoleWindow();
        if (hw == IntPtr.Zero) AllocConsole();
        Console.Clear();
        ShowWindow(hw, 8);
        Console.WriteLine("Start");
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        IntPtr hw = GetConsoleWindow();
        if (hw != IntPtr.Zero) ShowWindow(hw, 0);
    }
    
    [DllImport("kernel32.dll")]
    private static extern IntPtr GetConsoleWindow();
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);


    • Edited by Viorel_MVP Saturday, March 23, 2013 3:53 PM
    • Marked as answer by Kriss_p Sunday, March 24, 2013 6:13 PM
    Saturday, March 23, 2013 3:53 PM
  • Thank Viorel

    I have successfully used yours solution, now the console works well on Windows 7 and Windows 8.

    I also noticed that I had greater problems with the console (AllocConsole, FreeConsole) as runing project in debug mode (excpetion – invalid handle), but much less of a problem when runing the project without debugging (Ctrl + F5).

    Sunday, March 24, 2013 6:12 PM