【问题标题】:Java - JNA - User32.INSTANCE.GetLayeredWindowAttributes returns wrong transparency value [duplicate]Java - JNA - User32.INSTANCE.GetLayeredWindowAttributes 返回错误的透明度值 [重复]
【发布时间】:2021-04-14 22:36:41
【问题描述】:

经过多年在这里寻找答案,这个案例我找不到任何东西,所以我在这里发布问题

我尝试使用 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 代码返回错误值,我不知道为什么。

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

谢谢!

【问题讨论】:

    标签: java winapi jna


    【解决方案1】:

    我仍然不知道为什么会发生,但我想出了一个解决方法来修复返回值

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      相关资源
      最近更新 更多