I’m trying to find a way to get the current window’s text.
So using the win32-api gem I wrote this code using some help from this page
require 'win32/api'
include Win32
hWnd = GetActiveWindow = API.new('GetActiveWindow', 'V', 'L', 'user32').call
GetWindowText = API.new('GetWindowText', 'LPI', 'I', 'user32')
GetWindowTextLength = API.new('GetWindowTextLength', 'L', 'I', 'user32')
buf_len = GetWindowTextLength.call(hwnd)
str = ' ' * (buf_len + 1)
# Retreive the text.
result = GetWindowText.call(hwnd, str, str.length)
puts str.strip
The output is just an empty string because buf_len is always calculated as 0 due to hwnd being set as 0.
I can’t figure out why the hwnd returned is always just a 0.
As previously commented
GetActiveWindowwill only retrieve the window attached to the calling thread’s message queue. If you want to get a handle to the window that the user is currently regardless of what process it is running in try calling GetForegroundWindow rather thanGetActiveWindow.