Created
September 15, 2020 20:29
-
-
Save EliCDavis/5374fa4947897b16a81f6550d142ab28 to your computer and use it in GitHub Desktop.
Find Windows Handle Of Application In Golang
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
package main | |
import ( | |
"fmt" | |
"log" | |
"syscall" | |
"unsafe" | |
) | |
var ( | |
user32 = syscall.MustLoadDLL("user32.dll") | |
procEnumWindows = user32.MustFindProc("EnumWindows") | |
procGetWindowTextW = user32.MustFindProc("GetWindowTextW") | |
) | |
func EnumWindows(enumFunc uintptr, lparam uintptr) (err error) { | |
r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, uintptr(enumFunc), uintptr(lparam), 0) | |
if r1 == 0 { | |
if e1 != 0 { | |
err = error(e1) | |
} else { | |
err = syscall.EINVAL | |
} | |
} | |
return | |
} | |
func GetWindowText(hwnd syscall.Handle, str *uint16, maxCount int32) (len int32, err error) { | |
r0, _, e1 := syscall.Syscall(procGetWindowTextW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(str)), uintptr(maxCount)) | |
len = int32(r0) | |
if len == 0 { | |
if e1 != 0 { | |
err = error(e1) | |
} else { | |
err = syscall.EINVAL | |
} | |
} | |
return | |
} | |
func FindWindow(title string) (syscall.Handle, error) { | |
var hwnd syscall.Handle | |
cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr { | |
b := make([]uint16, 200) | |
_, err := GetWindowText(h, &b[0], int32(len(b))) | |
if err != nil { | |
// ignore the error | |
return 1 // continue enumeration | |
} | |
if syscall.UTF16ToString(b) == title { | |
// note the window | |
hwnd = h | |
return 0 // stop enumeration | |
} | |
return 1 // continue enumeration | |
}) | |
EnumWindows(cb, 0) | |
if hwnd == 0 { | |
return 0, fmt.Errorf("No window with title '%s' found", title) | |
} | |
return hwnd, nil | |
} | |
func main() { | |
const title = "Application Title" | |
h, err := FindWindow(title) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("Found '%s' window: handle=0x%x\n", title, h) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment