【问题标题】:How windows executable knows whether it is opened from consolewindows可执行文件如何知道它是否从控制台打开
【发布时间】:2021-07-14 04:01:58
【问题描述】:
【问题讨论】:
标签:
windows
powershell
console
【解决方案1】:
让我们找出答案!这是一个开源项目,所以代码都在那里供探索(双关语)。
首先,克隆存储库以便于搜索:git clone https://github.com/git-lfs/git-lfs.git。也可以通过 Github 搜索,但使用本地副本更容易。
然后,使用grep之类的工具,找到一条错误信息:
grep -r "command line tool" *
vendor/github.com/spf13/cobra/cobra.go:var MousetrapHelpText string = `This is a command line tool.
vendor/github.com/inconshreveable/mousetrap/README.md:Windows developers unfamiliar with command line tools will often "double-click"
看起来有一个包含消息的字符串。捕鼠器是什么东西,用在什么地方?
grep -r "MousetrapHelpText" *
vendor/github.com/spf13/cobra/cobra.go:// MousetrapHelpText enables an information splash screen on Windows
vendor/github.com/spf13/cobra/cobra.go:var MousetrapHelpText string = `This is a command line tool.
vendor/github.com/spf13/cobra/command_win.go: if MousetrapHelpText != "" && mousetrap.StartedByExplorer() {
vendor/github.com/spf13/cobra/command_win.go: c.Print(MousetrapHelpText)
看起来很有趣。让我们去https://github.com/inconshreveable/mousetrap获取源代码。 command_win.go 文件包含魔法。
TL;DR:Windows 进程的启动信息包含父进程 ID。如果是同一个 Explorer.exe(Win GUI shell),假设 GUI 启动。