如何在C#中关闭/打开控制台使用Win32调用? [英] How to close / open console within C# using Win32 calls?
问题描述
以下程序的Console.ReadKey()抛出一个错误。
The following program throws an error on "Console.ReadKey()".
如何禁用它后,我重新启用控制台?
How do I re-enable the console after disabling it?
using System;
using System.Threading;
using System.Runtime.InteropServices;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem((o) =>
{
Thread.Sleep(1000);
IntPtr stdin = GetStdHandle(StdHandle.Stdin);
CloseHandle(stdin);
});
Console.ReadLine();
Console.Write("ReadLine() successfully aborted by background thread.\n");
Console.Write("[any key to exit]");
Console.ReadKey(); // Throws an exception "Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read."
}
// P/Invoke:
private enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 };
[DllImport("kernel32.dll")]
private static extern IntPtr GetStdHandle(StdHandle std);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hdl);
}
}
额外专家
如果你想知道,我需要能够杀死后台线程运行的ReadLine(),在C#。这似乎是唯一的出路(Thread.Abort的将无法工作,因为的ReadLine()根深蒂固操作系统的肠子内,在不受控code)。有关于计算器这个话题谈了很多,没有人真正发现(或邮寄)终止到Console.ReadLine()还没有一个令人满意的方法。我想,这code是在正确的轨道上 - 只要我们能够将其禁用后重新启用控制台
If you're wondering, I need to be able to kill a background thread running ReadLine(), within C#. This appears to be the only way (thread.Abort won't work because ReadLine() runs deep within the bowels of the operating system, in unmanaged code). There is a lot of talk on this topic on StackOverflow, nobody has really discovered (or posted) a satisfactory method of aborting Console.ReadLine() yet. I think this code is on the right track - if only we can re-enable the console after disabling it.
推荐答案
不知道是否有帮助,但是当我需要能够写入到一个双赢的形式应用程序控制台,我用这个类:
Don't know if it helps, but when I've needed to be able to write to the console in a win form app, I've used this class:
public class ConsoleHelper
{
/// <summary>
/// Allocates a new console for current process.
/// </summary>
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
/// <summary>
/// Frees the console.
/// </summary>
[DllImport("kernel32.dll")]
public static extern Boolean FreeConsole();
}
呼叫AllocConsole创建一个控制台,然后可以写入(和读取)它。然后调用FreeConsole时,即可大功告成。
Call AllocConsole to create a console and then you can write to (and read from) it. Then call FreeConsole when you're done.
这篇关于如何在C#中关闭/打开控制台使用Win32调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!