Skip to content

Instantly share code, notes, and snippets.

@vxcute
Created February 11, 2023 19:19
Show Gist options
  • Save vxcute/66cbb98a815b8541ead01c4b30f8e549 to your computer and use it in GitHub Desktop.
Save vxcute/66cbb98a815b8541ead01c4b30f8e549 to your computer and use it in GitHub Desktop.
// simple example on using win32 api from golang
package main
import (
"errors"
"fmt"
"log"
"unsafe"
win "golang.org/x/sys/windows"
)
func GetProcessIdFromName(n string) (uint32, error) {
handle, err := win.CreateToolhelp32Snapshot(win.TH32CS_SNAPPROCESS, 0)
if err != nil {
return 0, err
}
procEntry := win.ProcessEntry32{}
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
err = win.Process32First(handle, &procEntry)
if err != nil {
return 0, err
}
for win.Process32Next(handle, &procEntry) == nil {
exeFile := win.UTF16ToString(procEntry.ExeFile[:])
if exeFile == n {
return procEntry.ProcessID, nil
}
}
return 0, errors.New("process not found")
}
func main() {
id, err := GetProcessIdFromName("brave.exe")
if err != nil {
log.Fatal(err)
}
fmt.Println("brave processId: ", id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment