2021-12-07 12:31:39 +00:00
|
|
|
package mousetrap
|
|
|
|
|
|
|
|
import (
|
|
|
|
"syscall"
|
|
|
|
"unsafe"
|
|
|
|
)
|
|
|
|
|
2023-04-10 11:14:21 +01:00
|
|
|
func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
|
|
|
|
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2021-12-07 12:31:39 +00:00
|
|
|
}
|
2023-04-10 11:14:21 +01:00
|
|
|
defer syscall.CloseHandle(snapshot)
|
|
|
|
var procEntry syscall.ProcessEntry32
|
|
|
|
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
|
|
|
|
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
|
|
|
|
return nil, err
|
2021-12-07 12:31:39 +00:00
|
|
|
}
|
|
|
|
for {
|
2023-04-10 11:14:21 +01:00
|
|
|
if procEntry.ProcessID == uint32(pid) {
|
|
|
|
return &procEntry, nil
|
2021-12-07 12:31:39 +00:00
|
|
|
}
|
2023-04-10 11:14:21 +01:00
|
|
|
err = syscall.Process32Next(snapshot, &procEntry)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2021-12-07 12:31:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
|
|
|
// on the executable from explorer.exe
|
|
|
|
//
|
|
|
|
// It is conservative and returns false if any of the internal calls fail.
|
|
|
|
// It does not guarantee that the program was run from a terminal. It only can tell you
|
|
|
|
// whether it was launched from explorer.exe
|
|
|
|
func StartedByExplorer() bool {
|
2023-04-10 11:14:21 +01:00
|
|
|
pe, err := getProcessEntry(syscall.Getppid())
|
2021-12-07 12:31:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
2023-04-10 11:14:21 +01:00
|
|
|
return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
|
2021-12-07 12:31:39 +00:00
|
|
|
}
|