当我尝试在WPF中将其打开两次时,控制台崩溃了 [英] the console crashed when i try to open it twice in wpf

查看:82
本文介绍了当我尝试在WPF中将其打开两次时,控制台崩溃了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用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();
        }
    }
}

推荐答案

如果您想继续分配一个新的控制台,然后为该新控制台使用ReadLine(),似乎还需要重新分配Console类的输入流.控制台:

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();
}

这就是说,我认为您确实在朝着错误的方向前进.控制台窗口是与用户进行交互的一种非常有限的方式.这就是为什么我们首先使用GUI程序(Winforms,WPF等)的原因.与遇到与托管程序中的非托管调用混合相关的不熟悉的错误相比,这几乎没有什么困难,并且当然也方式要少,您可以为您的程序创建一个窗口,该窗口可以执行控制台窗口的所有工作,但是做得更好.恕我直言,这确实是正确的方法.

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.

这篇关于当我尝试在WPF中将其打开两次时,控制台崩溃了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆