无法使用Jython + JNA获取当前前景窗口标题

时间:2014-01-22 07:23:18

标签: java windows jython jna

我正在尝试使用JNA和Jython获取当前的前景窗口标题。我的代码只是Java代码的翻译,以实现相同的目标。 Java中的代码工作 - 我已经测试过了 - 并且从这里开始:https://stackoverflow.com/a/10315344/1522521

当我致电GetLastError()时,我会回复1400代码,即ERROR_INVALID_WINDOW_HANDLE - 说明窗口句柄无效。我确信窗口句柄是正确的,因为我可以成功调用GetWindowTextLength(); ShowWindow(handle, WinUser.SW_MINIMIZE);ShowWindow(handle, WinUser.SW_MAXIMIZE);来获取标题的长度(看起来是正确的)并操纵窗口。

我有预感,问题在于我如何使用变量text作为GetWindowText()的参数。根据JNA的Javadoc,它假设是char[]缓冲区,JNA可以复制文本。因为我只是传递'字符串',它可能是不正确的。这是我的代码:

    def get_current_window_text():
        """
        Get current foreground window title.
        """
        handle = User32.INSTANCE.GetForegroundWindow()
        if User32.INSTANCE.IsWindowVisible(handle):
            print "Text lenght:", User32.INSTANCE.GetWindowTextLength(handle)

            max_length = 512
            text = ''
            result = User32.INSTANCE.GetWindowText(handle, text, max_length)
            print "Copied text length:", result
            if result:
                print "Window text:", text
                return result

            else:
                last_error_code = Kernel32.INSTANCE.GetLastError()
                if last_error_code == Kernel32.ERROR_INVALID_WINDOW_HANDLE:
                    print "[ERROR] GetWindowText: Invalid Window handle!"

                else:
                    print "[ERROR] Unknown error code:", last_error_code

        else:
            print "[ERROR] Current window is not visible"

1 个答案:

答案 0 :(得分:0)

我的预感是正确的,调用GetWindowText()时问题是参数不正确。它假设是char[] - 而不是Jython变量。这让我更多地研究并找到我以前不知道的东西--Jython中的Java数组。如Jython文档中所述http://www.jython.org/archive/21/docs/jarray.html

Many Java methods require Java array objects as arguments. The way that these arguments are used means that they must correspond to fixed-length, mutable sequences, sometimes of primitive data types. The PyArray class is added to support these Java arrays and instances of this class will be automatically returned from any Java method call that produces an array. In addition, the "jarray" module is provided to allow users of Jython to create these arrays themselves, primarily for the purpose of passing them to a Java method.

文档也有映射表。工作代码将是这样的:

import jarray    

text_length = User32.INSTANCE.GetWindowTextLength(handle)
max_length = 512
text = jarray.zeros(text_length, 'c')  
result = User32.INSTANCE.GetWindowText(handle, text, max_length)
print 'Copied text:', result