Created
January 21, 2022 15:47
-
-
Save maracko/e8de3f2bb3edf9046600c9167321c836 to your computer and use it in GitHub Desktop.
Get windows process handle in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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