C#里怎么才能让控制台ReadKey不阻塞程序

C艾斯蒂嗯蟹 2020-12-30 09:56:03
如下代码按一个键才能显示i,怎么才能不影响输入的情况下又能让I不停地自增

int i = 0;
while (true)
{
Console.ReadKey(true);
++i;
Console.SetCursorPosition(0,0);
Console.Write(i);
}


C++里可以用kbhit来实现,C#里有没有类似的方法

int i = 0;
while (true)
{
if(_kbhit()){
char ch = _getch();
}
cout << ++i << endl;
}
...全文
394 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wanghui0380 2020-12-30
  • 打赏
  • 举报
回复
引用
Alternative Managed API: This is in the .NET 2.0 Console class functions System.Console.KeyAvailable() or System.Console.ReadKey(). System.Console.KeyAvailable() - Gets a value indicating whether a key press is available in the input stream. (Nonblocking) System.Console.ReadKey() - Obtains the next character or function key pressed by the user. Allows for both echoing key to screen or not.
wanghui0380 2020-12-30
  • 打赏
  • 举报
回复
http://www.pinvoke.net/default.aspx/msvcrt/kbhit.html [DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)] static extern int kbhit();
wanghui0380 2020-12-30
  • 打赏
  • 举报
回复
[DllImport("crtdll.dll")] public static extern int _kbhit(); 有可以有,不过没有特殊需要我们不建议使用。 和某园子不同的是,我们不建议程序员们在没有特殊需要的时候,去飞檐走壁。并把这些玩意当作很NB的东西,去大书特书
The 祺℡ 2020-12-30
  • 打赏
  • 举报
回复
重新开个Thread去++i呀。readkey和++i都在主线程里,必定阻塞

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧