2013-08-18 74 views
2

我有一个C#控制台应用程序下面的代码:问题涉及到在C#控制台应用程序NET

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine("Hello..."); 
    } 
} 

当我运行该应用程序,命令提示符出现和突然消失了,但我在看过当我运行应用程序时,我的朋友的房子,命令提示符要求Press any key to Continue。当我按任意键后,应用程序终止..,但在我的电脑不工作,没有写Consol.ReadLine()

是否有一个设置让用户访问Press Any Key to Continue行?

+0

它是因为您的程序在完成后退出 – Rohit

回答

5

可悲的是没有,但如果你调试 - >不开始调试Ctrl + F5键它将使这种效果。

很明显,你可以在你的程序的末尾添加

Console.Write("\nPress Any Key to Continue"); 
Console.Readkey(); 

如果你想成为(几乎)确保您的代码将始终显示提示:

AppDomain.CurrentDomain.ProcessExit += (sender, e) => 
{ 
    Console.Write("\nPress Any Key to Continue"); 
    Console.ReadKey(); 
}; 

把这些线在你Main()方法的开始。

但我认为这有点过分了:-)它安装了一个退出处理程序,它会在退出时要求一个键。现在

,如果你想真的真的太过火和表演,你可以去多达11个:

if (Debugger.IsAttached) 
{ 
    AppDomain.CurrentDomain.ProcessExit += (sender, e) => 
    { 
     Console.Write("\nPress Any Key to Continue"); 
     Console.ReadKey(); 
    }; 
} 

这将要求只有在调试器附着(即使这些线必须是关键放在Main()方法的开头,它们替换了其他版本)。与Start Without Debugging调试器不是附加,所以Visual Studio将显示其提示而不是你的。

(而不是使用AppDomain.CurrentDomain.ProcessExit的,你可以有一个try...finally块保护整个Main()方法,并在最后放Console.*,但是这一点也不好笑:-))

0

消失正确的行为。如果您希望它以这种方式出现,只需添加 Console.ReadKey();当然,您可以在之前添加一些消息(“按任意键...”)等。