Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

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

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();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...