blob: 9a28e57c3c30bd44ab31b5743cfc5178a6bc3a19 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001// +build windows
2// +build go1.4
3
4package mousetrap
5
6import (
7 "os"
8 "syscall"
9 "unsafe"
10)
11
12func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
13 snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
14 if err != nil {
15 return nil, err
16 }
17 defer syscall.CloseHandle(snapshot)
18 var procEntry syscall.ProcessEntry32
19 procEntry.Size = uint32(unsafe.Sizeof(procEntry))
20 if err = syscall.Process32First(snapshot, &procEntry); err != nil {
21 return nil, err
22 }
23 for {
24 if procEntry.ProcessID == uint32(pid) {
25 return &procEntry, nil
26 }
27 err = syscall.Process32Next(snapshot, &procEntry)
28 if err != nil {
29 return nil, err
30 }
31 }
32}
33
34// StartedByExplorer returns true if the program was invoked by the user double-clicking
35// on the executable from explorer.exe
36//
37// It is conservative and returns false if any of the internal calls fail.
38// It does not guarantee that the program was run from a terminal. It only can tell you
39// whether it was launched from explorer.exe
40func StartedByExplorer() bool {
41 pe, err := getProcessEntry(os.Getppid())
42 if err != nil {
43 return false
44 }
45 return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
46}