trap_windows.go 1.1 KB

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