4

我试图找到一种方法来获取当前窗口的文本。因此,我使用 win32-api gem 使用此页面的一些帮助编写了此代码

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

输出只是一个空字符串,因为由于 hwnd 设置为 0,buf_len 始终计算为 0。我无法弄清楚为什么返回的 hwnd 始终只是 0。

4

1 回答 1

1

如前所述GetActiveWindow,只会检索附加到调用线程的消息队列的窗口。如果您想获取用户当前所在窗口的句柄,而不管它在哪个进程中运行,请尝试调用GetForegroundWindow而不是GetActiveWindow.

检索前台窗口(用户当前正在使用的窗口)的句柄。

于 2013-01-08T19:15:52.120 回答