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();
}
}
}
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 usingReadLine()
for that new console: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.