using System;
using System.Timers;class myApp
{
    public static void Main()
    {
        Timer myTimer = new Timer(); 
        myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);  
        myTimer.Interval = 1000;
        myTimer.Start();        while (Console.Read() != 'q')
        {
            ; //do nothing...
            Console.WriteLine("----------------------------");
        }
    }
  
    public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
    {
        Console.Write("\r{0}", DateTime.Now);
    }
}我的问题就是Console.WriteLine("----------------------------"); 当定时器计时的时候,输入"q"以外的字母While会循三次Console.WriteLine("----------------------------"); 为什么呢?

解决方案 »

  1.   

    while (Console.ReadLine() != "q")
      

  2.   

    你最好使用readkey方法,接受输入的键来判断
    三次:keydown,keypress,keyup,应该是这三次了
      

  3.   

    因为你用了Console.ReadLine()
    这样你敲一个q,读入的是"q/r/n",最后两个是换行和回车,所以就有问题了楼主可以用Console.ReadKey(),判断语句这样写while (Console.ReadKey() != Keys.Q)
      

  4.   

    using System; 
    using System.Timers; class myApp 

        public static void Main() 
        { 
            Timer myTimer = new Timer(); 
            myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);  
            myTimer.Interval = 1000; 
            myTimer.Start();         while (Console.ReadKey().KeyChar!= 'q') 
            { 
                ; //do nothing... 
                Console.WriteLine("----------------------------"); 
            } 
        } 
      
        public static void DisplayTimeEvent(object source, ElapsedEventArgs e) 
        { 
            Console.Write("\r{0}", DateTime.Now); 
        }