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