废话不多说直接上代码,很多人在写程序时双击打开都会一闪而逝,因此都会在程序执行最后加上获取输入的代码。但是命令行时又不想再敲一次回车。下面代码就能解决你的烦恼,原理就是判断父进程是否为cmd.exe,如果不是则说明不是命令行打开,则加上获取输入回车。
package main
import (
"fmt"
"syscall"
"unsafe"
)
func main() {
if name, err := getParentProcessName(); err == nil && name != "cmd.exe" {
defer fmt.Scanln() // 不是命令行时避免一闪而逝
}
fmt.Println("hello word!")
}
func getParentProcessName() (string, error) {
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
if err != nil {
return "", err
}
defer syscall.CloseHandle(snapshot)
var procEntry syscall.ProcessEntry32
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
return "", err
}
var (
pid = uint32(syscall.Getpid())
pName = make(map[uint32]string, 32)
parentId = uint32(1<<32 - 1)
)
for {
pName[procEntry.ProcessID] = syscall.UTF16ToString(procEntry.ExeFile[:])
if procEntry.ProcessID == pid {
parentId = procEntry.ParentProcessID
}
if s, ok := pName[parentId]; ok {
return s, nil
}
err = syscall.Process32Next(snapshot, &procEntry)
if err != nil {
return "", err
}
}
}