java-jna-user32.instance.getlayeredwindowattributes返回错误的透明度值

toe95027  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(439)

这个问题在这里已经有答案了

我们能在java中生成无符号字节吗(16个答案)
55分钟前关门了。
经过多年的寻找答案在这里,这个案件我找不到任何东西,所以我在这里张贴问题
我试着用它来获得某个窗口的透明度 GetLayeredWindowAttributes win32 api中的函数。
在c++/c中,为了获得透明度级别,我使用以下代码:

DWORD flags = LWA_ALPHA;
BYTE alpha;
if (GetLayeredWindowAttributes(target_hwnd, nullptr, &alpha, &flags))
{
  // Here I got the value inside alpha variable
}

在java+jna中,我没有找到任何简单的例子。但我觉得我来的时候有些东西应该有用。以下是我在java中所做的:

ByteByReference alpha = new ByteByReference();
if (User32.INSTANCE.GetLayeredWindowAttributes(windowHwnd,null,alpha,new IntByReference((byte) 0x00000002))) {
    // Here I got the transparency in alpha.getValue()
}

问题是由于某种原因,java代码将返回 -27 而c代码将返回相同的窗口 229 这是正确的值。
我注意到当透明度 255 ,两个代码(java和c
)都将返回 255 但是由于某种原因,java代码返回了错误的值,我不知道为什么。
你知道我做错了什么,怎么解决吗?
谢谢!

ee7vknir

ee7vknir1#

我仍然不知道为什么会发生这种情况,但是我找到了一个解决方法来修复返回值

public static int getWindowTransparency(WinDef.HWND windowHwnd) {
    ByteByReference alpha = new ByteByReference();
    // According to my tests, this API call will return false when the transparency is 255 (This is unlike when using it from C)
    // so we just assume it as 255 and return 255
    if (!User32.INSTANCE.GetLayeredWindowAttributes(windowHwnd, null, alpha, new IntByReference((byte) 0x00000002)))
        return 255;

    int transparency = alpha.getValue();

    // Here we fix some strange behavior that the value may be negative.
    // This will fix it and make sure it between 0 and 255
    if (transparency < 0)
        transparency = 128 + (128 - Math.abs(transparency));

    return transparency;
}

如果这是错误的,请让我知道,我会更新答案。谢谢。
我对它进行了测试,并将结果与c++版本进行了比较,结果似乎始终返回正确的值。

相关问题