How to tell if there is a console

前端 未结 10 2211
庸人自扰
庸人自扰 2020-12-14 16:34

I\'ve some library code that is used by both console and WPF apps. In the library code, there are some Console.Read() calls. I only want to do those input rea

10条回答
  •  -上瘾入骨i
    2020-12-14 17:14

    This SO question may provide you a solution.

    Another solution is:

    Console.Read() returns -1 in windows forms applications without opening up a console window. In a console app, it returns the actual value. So you can write something like:

    int j = Console.Read();
    if (j == -1)
        MessageBox.Show("It's not a console app");
    else
        Console.WriteLine("It's a console app");
    

    I tested this code on console and winforms apps. In a console app, if the user inputs '-1', the value of j is 45. So it will work.

提交回复
热议问题