Skip to content

Instantly share code, notes, and snippets.

@maracko
Created January 21, 2022 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maracko/e8de3f2bb3edf9046600c9167321c836 to your computer and use it in GitHub Desktop.
Save maracko/e8de3f2bb3edf9046600c9167321c836 to your computer and use it in GitHub Desktop.
Get windows process handle in Go
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"time"
"unsafe"
"golang.org/x/sys/windows"
)
func main() {
ProcessUtils{}.SetWinNice(13716, windows.HIGH_PRIORITY_CLASS)
}
var (
kernel32 = syscall.MustLoadDLL("kernel32.dll")
procOpenProcess = kernel32.MustFindProc("OpenProcess")
)
const PROCESS_ALL_ACCESS = 0x1F0FFF
type ProcessUtils struct {
}
func (ProcessUtils) GetProcessHandle(pid int) windows.Handle {
handle, _, _ := procOpenProcess.Call(ToUintptr(PROCESS_ALL_ACCESS), ToUintptr(true), ToUintptr(pid))
return windows.Handle(handle)
}
func (u ProcessUtils) SetWinNice(pid int, priority uint32) error {
handle := u.GetProcessHandle(pid)
return windows.SetPriorityClass(handle, priority)
}
func ToUintptr(val interface{}) uintptr {
switch t := val.(type) {
case string:
p, _ := syscall.UTF16PtrFromString(val.(string))
return uintptr(unsafe.Pointer(p))
case int:
return uintptr(val.(int))
default:
_ = t
return uintptr(0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment