tcl pause & waiting for key pressed to continue

北战南征 提交于 2019-12-05 14:08:44

With gratitude to Hai Vu's answer, if you're on a unix-like system with stty

proc anykey {{msg "Hit any key: "}} {
    set stty_settings [exec stty -g]
    exec stty raw -echo
    puts -nonewline $msg
    flush stdout
    read stdin 1
    exec stty $stty_settings
    puts ""
}
puts 1
anykey
puts 2

Link to thorough discussion on Tcl wiki: Reading a single character from the keyboard using Tcl

You just use gets to read from stdin:

proc pause {{message "Hit Enter to continue ==> "}} {
    puts -nonewline $message
    flush stdout
    gets stdin
}

pause "Hurry, hit enter: "; # Sample usage 1
pause;                      # Sample usage 2, use default message
robert4

A potential solution for Windows:

exec -ignorestderr [file join $env(windir) system32 cmd.exe] /c pause

This notices non-ascii keypresses, too (such as arrow keys, Escape etc.).

Another solution is the Raw Mode on Windows proposed by Donal Fellows above (thanks for the link!), which can be summarized into these two lines of code:

twapi::modify_console_input_mode stdin -lineinput 0 -echoinput 0
read stdin 1

This does not notice Escape, arrows keys and the like (and you may need to restore the console input mode later).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!