#Requires AutoHotkey v2.0
#SingleInstance Force
; === Ziel-Fenster aus Window Spy ===
Sel := "ahk_exe HmiRTm.exe ahk_class HmiRTm"
; Skalierung (0.85 = 85 % der Arbeitsfläche)
Scale := 0.85
; Win32-Flags
GWL_STYLE := -16
WS_CAPTION := 0x00C00000
WS_THICKFRAME := 0x00040000
WS_SYSMENU := 0x00080000
WS_MINIMIZEBOX := 0x00020000
WS_MAXIMIZEBOX := 0x00010000
SWP_FRAMECHANGED := 0x0020
SWP_NOZORDER := 0x0004
; alle 500 ms prüfen
SetTimer(Monitor, 500)
; Tray-Menü
A_TrayMenu.Delete()
A_TrayMenu.Add("Script beenden", (*) => ExitApp())
return
Monitor() {
    static lastHwnd := 0, lastMon := 0
    global Sel, Scale
    hwnd := WinExist(Sel)
    if !hwnd
        return
    ApplyBorderless(hwnd)
    mon := GetMonitorFromWindow(hwnd)
    if (hwnd != lastHwnd) || (mon != lastMon) || NeedResize(hwnd, mon, Scale) {
        CenterToPercentOfWorkArea(hwnd, mon, Scale)
        lastHwnd := hwnd, lastMon := mon
    }
}
ApplyBorderless(hwnd) {
    global GWL_STYLE, WS_CAPTION, WS_THICKFRAME, WS_SYSMENU, WS_MINIMIZEBOX, WS_MAXIMIZEBOX
    global SWP_FRAMECHANGED, SWP_NOZORDER
    style := DllCall("GetWindowLongPtr", "ptr", hwnd, "int", GWL_STYLE, "ptr")
    if (style & (WS_CAPTION|WS_THICKFRAME|WS_SYSMENU|WS_MINIMIZEBOX|WS_MAXIMIZEBOX)) {
        style &= ~(WS_CAPTION|WS_THICKFRAME|WS_SYSMENU|WS_MINIMIZEBOX|WS_MAXIMIZEBOX)
        DllCall("SetWindowLongPtr", "ptr", hwnd, "int", GWL_STYLE, "ptr", style)
        DllCall("SetWindowPos", "ptr", hwnd, "ptr", 0
            , "int", 0, "int", 0, "int", 0, "int", 0
            , "uint", SWP_FRAMECHANGED|SWP_NOZORDER)
    }
}
GetMonitorFromWindow(hwnd) {
    WinGetPos &x, &y, &w, &h, "ahk_id " hwnd
    cx := x + w/2, cy := y + h/2
    cnt := MonitorGetCount(), mon := 1
    loop cnt {
        MonitorGet A_Index, &L, &T, &R, &B
        if (cx >= L && cx <= R && cy >= T && cy <= B) {
            mon := A_Index
            break
        }
    }
    return mon
}
NeedResize(hwnd, mon, scale) {
    WinGetPos &x, &y, &w, &h, "ahk_id " hwnd
    MonitorGetWorkArea mon, &L, &T, &R, &B
    NW := Round((R-L) * scale), NH := Round((B-T) * scale)
    NX := L + (R-L-NW)//2, NY := T + (B-T-NH)//2
    tol := 2
    return (Abs(w-NW) > tol) || (Abs(h-NH) > tol) || (Abs(x-NX) > tol) || (Abs(y-NY) > tol)
}
CenterToPercentOfWorkArea(hwnd, mon, scale) {
    global SWP_NOZORDER, SWP_FRAMECHANGED
    MonitorGetWorkArea mon, &L, &T, &R, &B
    NW := Round((R-L) * scale), NH := Round((B-T) * scale)
    NX := L + (R-L-NW)//2, NY := T + (B-T-NH)//2
    DllCall("SetWindowPos", "ptr", hwnd, "ptr", 0
        , "int", NX, "int", NY, "int", NW, "int", NH
        , "uint", SWP_NOZORDER|SWP_FRAMECHANGED)
}