Page 1 of 1

How to send ControlClick to game window ragardless its active state?

Posted: 22 Apr 2024, 04:33
by tetratheta
I want to send mouse click (and keyboard key later) to a game, even though the game window is not active.

Code: Select all

#Requires AutoHotkey v2.0
#SingleInstance Force
InstallKeybdHook(True, True)
InstallMouseHook(True, True)
DetectHiddenWindows(True)

target_hwnd := 0
target_title := "Granblue Fantasy: Relink"
target_exe := "granblue_fantasy_relink.exe"

#HotIf WinExist(target_title)
$F2::RepeatKey()
$F3::StopKey()
#HotIf

FindWindow(title, exe) {
  global target_hwnd
  try {
    local thwnd := WinGetID("ahk_class " . title . " ahk_exe " . exe)
    target_hwnd := thwnd
    return True
  } catch TargetError {
    target_hwnd := 0
    return False
  }
}
RepeatKey() {
  global target_title, target_exe, target_hwnd
  if (FindWindow(target_title, target_exe)) {
    Loop 600 {
      if (!PressKey(target_hwnd)) {
        Sleep(200)
      } else {
        break
      }
    }
  } else {
    SoundPlay("*16")
  }
}
PressKey(hwnd) {
  ; SendEvent("{LButton Down}")
  ; Sleep(20)
  ; SendEvent("{LButton Up}")
  try {
    ControlClick(,"ahk_id " . hwnd,,,, "D")
    Sleep(20)
    ControlClick(,"ahk_id " . hwnd,,,, "U")
    return True
  } catch Error as err {
    SoundPlay("*16")
    MsgBox(Format("{1}: {2}.`n`nFile:`t{3}`nLine:`t{4}`nWhat:`t{5}`nStack:`n{6}", type(err), err.Message, err.File, err.Line, err.What, err.Stack))
    return False
  }
}
StopKey() {
  SendEvent("{LButton Up}")
  Sleep(5)
  SoundPlay("*16")
  Reload()
}
Strange thing is, SendEvent works while the game window is active, but ControlClick doesn't work even though the game window is active.

I don't know why this problem happens. Maybe this can be related, but what I want to send currently is mouse click, not keyboard key.

I was planning to add more things that sends keyboard keys, but since my script can't even send mouse click, I can't go further.

Here is a thing I've found.
  • Mouse cursor is captured by the game window (cursor is not visible), and its position is fixed to center of the screen.