the console crashed when i try to open it twice in wpf

丶灬走出姿态 提交于 2019-12-12 06:39:54

问题


I want to open a console in wpf, I was try to open the console twice without close the program, but in the second time the program crashed, I don't really know why and I'd love to help

using System;
using System.Windows;
using System.Runtime.InteropServices;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        [DllImport("Kernel32")]
        public static extern void AllocConsole();

        [DllImport("Kernel32")]
        public static extern void FreeConsole();

        private void button_Click(object sender, RoutedEventArgs e)
        {
                AllocConsole();
                string x = Console.ReadLine();
                FreeConsole();
        }
    }
}

回答1:


It looks like you need to also reallocate the Console class's input stream if you want to keep allocating a new console and then using ReadLine() for that new console:

private void button_Click(object sender, RoutedEventArgs e)
{
    AllocConsole();

    using (Stream stream = Console.OpenStandardInput())
    using (TextReader reader = new StreamReader(stream))
    {
        string x = reader.ReadLine();
    }

    FreeConsole();
}

That said, I think you're really headed in the wrong direction with this. The console window is an extremely limited means for interacting with the user. It's why we have GUI programs in the first place (Winforms, WPF, etc.). With very little difficulty, and certainly way less difficulty than running into unfamiliar errors related to the mixing of unmanaged calls in your managed program, you can create a window for your program that does everything a console window does, but does it better. IMHO, that's really the right way to go.



来源:https://stackoverflow.com/questions/40142878/the-console-crashed-when-i-try-to-open-it-twice-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!