如何使用Win32调用在C#中关闭/打开控制台?
发布时间:2020-12-14 01:55:42 所属栏目:Windows 来源:网络整理
导读:以下程序在“Console.ReadKey()”上引发错误. 禁用后如何重新启用控制台? using System; using System.Threading; using System.Runtime.InteropServices; namespace ConsoleApplication { class Program { static void Main(string[] args) { ThreadPool.Q
以下程序在“Console.ReadKey()”上引发错误.
禁用后如何重新启用控制台? 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); } } 专家额外 如果您想知道,我需要能够在C#中杀死运行ReadLine()的后台线程.这似乎是唯一的方法(thread.Abort将无法工作,因为ReadLine()在操作系统的内部深处运行,在非托管代码中).在StackOverflow上有很多关于这个主题的讨论,没有人真正发现(或发布)一个令人满意的中止Console.ReadLine()的方法.我认为这段代码是正确的 – 如果只有我们可以在禁用它后重新启用它. 解决方法
不知道它是否有帮助,但是当我需要能够在win form应用程序中写入控制台时,我已经使用过这个类:
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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
推荐文章
站长推荐
- Windows上的单一登录和NFS权限
- windows-runtime – Windows Phone后台任务提前停
- windows-server-2008 – 两个本地网络,但Windows
- Windows存储ACL和ACL的位置遵循从一台计算机到另
- windows – 如何确定进程是否是当前活动/前台应用
- windows-xp – 如何在Windows XP中为可执行文件设
- windows-server-2008 – 如何使用Powershell确定
- 在windows下部署包含C3P0的war包没问题,部署到l
- windows – 在Mercurial中配置eol扩展的问题
- windows – 如何处理从Delphi 6和WinXP到Delphi
热点阅读