-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautostarter_windows.go
80 lines (70 loc) · 1.76 KB
/
autostarter_windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// +build windows
package autostarter
import (
"errors"
"os"
"path/filepath"
"github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
)
const shortcutExt = ".lnk"
type oleObject struct {
oleShellObject *ole.IUnknown
wShell *ole.IDispatch
}
func newShellObject() *oleObject {
ole.CoInitializeEx(0, ole.COINIT_APARTMENTTHREADED|ole.COINIT_SPEED_OVER_MEMORY)
oleShellObject, err := oleutil.CreateObject("WScript.Shell")
if err != nil {
oleShellObject.Release()
panic(err)
}
wShell, err := oleShellObject.QueryInterface(ole.IID_IDispatch)
if err != nil {
oleShellObject.Release()
wShell.Release()
panic(err)
}
return &oleObject{
oleShellObject: oleShellObject,
wShell: wShell,
}
}
func (o *oleObject) release() {
o.oleShellObject.Release()
o.wShell.Release()
}
func getStartupDir() (dir string) {
dir = filepath.Join(os.Getenv("APPDATA"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup")
return
}
func checkIcon(path string) error {
switch filepath.Ext(path) {
case ".ico":
default:
return errors.New("format invalid: " + filepath.Ext(path))
}
return nil
}
func createShortcut(sc Shortcut, ic icon) (err error) {
object := newShellObject()
defer object.release()
cs, err := oleutil.CallMethod(object.wShell, "CreateShortcut", filepath.Join(getStartupDir(), sc.Name+shortcutExt))
if err != nil {
return
}
iDispatch := cs.ToIDispatch()
oleutil.PutProperty(iDispatch, "TargetPath", sc.Exec)
if len(sc.Args) > 0 {
oleutil.PutProperty(iDispatch, "Arguments", sc.getArgsString())
}
oleutil.PutProperty(iDispatch, "WorkingDirectory", sc.StartIn)
if ic != "" {
oleutil.PutProperty(iDispatch, "IconLocation", string(ic))
}
_, err = oleutil.CallMethod(iDispatch, "Save")
if err != nil {
return
}
return
}