首页 | IT新闻 | 硬件 | 操作系统 | 开发 | 网络编程 | 数据库 | 热门框架 | 网络安全 | 组网 | 建站指南 | 网页制作 | 特效 | 实用技巧 | 服务器 | 办公 | QQ | 探索 | 社区

  • 技术部落
  • 部落首页 > 程序开发 > C/C#/C++ > 正文
  • 如何通过判断按键来退出循环
      2007-2-25  来源:网络资源  编辑:Jsbulo  热度:

           前几天在c#版中看到一个帖子:“如何用c#实现,在while (true)循环中,按Esc键退出循环?" 那时候以为只能用hook来监视键盘,看了看后面一些猩猩的回复,只怪自己c#太菜,都没有看明白:( 昨天在c版看到又有人问这个问题,其中cyberHunK(→迈克·老猫←) 用了_kbhit()来解决了这个问题,我又去查了查MSDN,才有点明白,终于知道了还有_kbhit()这样的函数(汗。。。)。觉得这个东西蛮有用的,就记下来,有错的地方还请各位指教!
    先抄一段MSDN对_kbhit()的解释:
    int _kbhit( void );
    Return Value
    _kbhit returns a nonzero value if a key has been pressed. Otherwise, it returns 0.

    Remarks
    The _kbhit function checks the console for a recent keystroke. If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch or _getche to get the keystroke.
    所以在vc里面可以用下面这个程序来实现按ESC退出while循环
    #include
    #include //包含对 _kbhit()和_getch()声明

    int main()
    {
    bool flag = true;
    char unch;
    while(flag)
    if(_kbhit() && (unch = _getch()) == 0x1b )
    flag = false; //ESC的键盘扫描码是0x1b
    return 0;
    } //vc6.0下编译运行通过
    呵呵,原来这么简单!基本的用法就是这样了,你可以在里面加些代码来实现复杂一些的功能。
    那类似这样的功能用c#该怎么实现呢?笨点儿的办法就是引用dll,在c#里面调用_kbhit()来实现。(因为_kbhit()是vc这个编译器特有的系统函数下面这个程序中就用到了这种方法,用于判断在3秒中内是否有键按下。(vs2005下编译运行通过)
    using System;
    using System.Runtime.InteropServices;
    using System.Threading;

    namespace ConsoleApplication2
    {
    class Program
    {
    [DllImport("msvcrt.dll")]
    public static extern int _getch();
    [DllImport("msvcrt.dll")]
    public static extern int _kbhit();

    static void Main(string[] args)
    {
    Console.WriteLine("Press Any Key to Continue");
    int counter = 0;

    while ((_kbhit() == 0) && counter < 30)
    {
    Thread.Sleep(100);
    counter++;
    }
    if (counter < 30)
    {
    Console.WriteLine("you pressed " + (char)_getch());
    }
    else
    {
    Console.WriteLine("You did not press anything using default after 3 seconds");
    }
    }
    }
    }
    子曾经曰过:“举一隅,不以三隅反,则不复也”。c#其实不用上面那种方法也可以比较容易的实现这个功能。(google出来的)
    程序如下:(程序不停的输出“循环中”,按a退出)
    using System;
    namespace ConsoleApplication2
    {
    class Program
    {
    static void Main(string[] args)
    {
    bool a = false;
    ConsoleKeyInfo keyInfo;
    while (!a)
    {
    if (System.Console.KeyAvailable)//如果有键按下
    {
    keyInfo = System.Console.ReadKey(true);//读取
    if (keyInfo.KeyChar == 0x1b)//判断
    a = true;
    }
    else
    System.Console.WriteLine("循环中");
    }

    }
    }
    }