简体   繁体   中英

How can I pause a C# Console application (only when being run by a user)

How can I pause a C# console application only while being run by a user?

I've searched similar issues on stack overflow which recommend learning to debug properly, using readline, etc, but none of them cover the instance where your process might be being run by an automated system that needs to continue straight past (ie not pause, to let user read screen).

How can I determine whether the console is being run interactively or by a script?

If this were bash on a linux system, I could do something like

https://www.gnu.org/software/bash/manual/html_node/Is-this-Shell-Interactive_003f.html

Using some command line argument would be the easiest solution. For example if program is run with command line parameter "-automatic" it could just run without stopping. Without such parameter program would run in interactive mode and would expect user input.

It is pretty standard approach used by many command line utilities.

You need to check if someone is logged in as the interactive user, but this is mostly for usage with services. Some "automated" systems since you mention such a term may be faking a logged-in user.

There are some suggestions available at: Check if no user is currently logged on to Windows

Probably the easiest way (especially if you don't want to rely on WMI API) is to enumerate user sessions via P/Invoke call, as shown here: http://www.pinvoke.net/default.aspx/wtsapi32/WTSEnumerateSessions.html

Console.OpenStandardInput(1) will return Stream.Null if the console Application is not being ran interactively.

    private static void pause()
    {
        if (Console.OpenStandardInput(1) != Stream.Null)
        {
            Console.Out.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM