Java-JNA-User32.INSTANCE.GetLayeredWindowAttributes返回错误的透明度值



在这里找到答案多年后,这个案例我什么都找不到,所以我在这里发布了关于的问题

我尝试在Win32 API中使用GetLayeredWindowAttributes函数来获取某些窗口的透明度级别。

在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代码返回了错误的值,我不知道为什么。

知道我做错了什么以及如何解决吗?

谢谢!

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


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++版本进行了比较,它似乎一直返回正确的值。

最新更新