Java Native Access

Using JNA to link to custom dll

how do I access custom .lib / .dll functions using JNA? Can someone provide an example?

Thank you.

Source: (StackOverflow)

Use JNI instead of JNA to call native code?

JNA seems a fair bit easier to use to call native code compared to JNI. In what cases would you use JNI over JNA?

Source: (StackOverflow)

Skip window from being captured

I have created an AIR application which has two windows. First one is main window(spark Windowed Application) and the second one is a component(spark window). I am using Java to capture the Desktop screen with Flex-Java Bridge Flerry.

Here is the code to capture the screen which is:-

HDC hdcWindow = User32.INSTANCE.GetDC(hWnd);
HDC hdcMemDC = GDI32.INSTANCE.CreateCompatibleDC(hdcWindow);
RECT bounds = new RECT();
User32Extra.INSTANCE.GetClientRect(hWnd, bounds);

int width = bounds.right;
int height = bounds.bottom ;
HBITMAP hBitmap = GDI32.INSTANCE.CreateCompatibleBitmap(hdcWindow, width, height);

HANDLE hOld = GDI32.INSTANCE.SelectObject(hdcMemDC, hBitmap);
GDI32Extra.INSTANCE.BitBlt(hdcMemDC, 0, 0, width, height, hdcWindow, 0, 0, WinGDIExtra.SRCCOPY);

I don't want the main flex window to be captured. It should skipped(transparent) from being captured.

Is that possible by changing the configuration of flex project?

If it cannot be done in flex and java, in what platform it can be done?

Source: (StackOverflow)

Get events from OS

I work on windows but I am stuck here on Mac. I have the Canon SDK and have built a JNA wrapper over it. It works well on windows and need some help with Mac. In the sdk, there is a function where one can register a callback function. Basically when an event occurs in camera, it calls the callback function.

On windows, after registering, I need to use User32 to get the event and to dispatch the event by:

private static final User32 lib = User32.INSTANCE;
boolean hasMessage = lib.PeekMessage( msg, null, 0, 0, 1 ); // peek and remove
if( hasMessage ){
    lib.TranslateMessage( msg ); 
    lib.DispatchMessage( msg ); //message gets dispatched and hence the callback function is called

In the api, I do not find a similar class in Mac. How do I go about this one??

PS: The JNA api for unix is extensive and I could not figure out what to look for. The reference might help

Source: (StackOverflow)

Getting active window information in Java

I am trying to upgrade my application in Java to work only if a window of process with certain name is active. I have found out that this is possible by using JNI, but I have no idea how exactly to do that. I just could not find any description or example that would explain it. My question is - how to get process name of currently active window in Windows (via JNI, or anything else - I accept any another solution)?

Source: (StackOverflow)

How do I properly map a `MagImageScalingCallback` using JNA?

I am using jna.jar, jna-3.2.5.jar and jna-3.3.0-platform.jar in my Java Project.

This is the Winapi function I want to replicate.

BOOL WINAPI MagImageScalingCallback(
  _In_  HWND           hwnd,
  _In_  void           *srcdata,
  _In_  MAGIMAGEHEADER srcheader,
  _Out_ void           *destdata,
  _In_  MAGIMAGEHEADER destheader,
  _In_  RECT           unclipped,
  _In_  RECT           clipped,
  _In_  HRGN           dirty

This is my Java code

public interface MagImageScalingCallback extends StdCallLibrary.StdCallCallback{
    public boolean MagImageScalingCallback(HWND hwnd,
            Pointer srcdata,
            MAGIMAGEHEADER.ByValue srcheader,
            Pointer destdata,
            MAGIMAGEHEADER.ByValue destheader,
            RectByValue source,
            RectByValue clipped,
            HRGN dirty);

When I get into this method of the callback, I get unexpected results:

    public boolean MagImageScalingCallback(HWND hwnd, Pointer srcdata,
            MAGIMAGEHEADER.ByValue srcheader, Pointer destdata,
            MAGIMAGEHEADER.ByValue destheader, RectByValue source, RectByValue clipped, HRGN dirty) {
        image.setRGB(0, 0, srcheader.width, srcheader.height, srcdata.getIntArray(0, srcheader.width * srcheader.height ), 0, srcheader.width);
        return true;

This table explains What works and what doesn't work in 32 bit and 64 bit system when I change the data type of the variables.

| Parameter    | Data type    |   64 bit    |   32 bit    |
| source       | WinDef.RECT  |   Working   | Not Working |
| clipped      | WinDef.RECT  |   Working   | Not Working |
| source       | RectByValue  |   Working   |   Working   |
| source       | RectByValue  |   Working   |   Working   |
| srcdata      | Pointer      |   Working   | Not Working |
| destdata     | Pointer      |   Working   | Not Working |

Not working means a totally black image in the result

If I use the above code in a 64 bit system, I can capture the desktop(I can access the data from the Pointer variable). If I use the same code in 32 bit system, I am not getting any image. You can see my whole code in the below link.

Why is the error in my code? How can I fix that?

For your Information. As you see in the, Whenever MagSetWindowSource function is called. MagImageScalingCallback(in line 80) is called.

Problems in this section of code

If I run this code on a 64 bit system srcdata and destdata will hold the array of integer pixels of the Desktop(If I save this as image, it captures the desktop). But if I run the same code on 32 bit system these both variable array pixel value is always zero(If I save the image, it is always black)

64 bit system enter image description here

32 bit system enter image description here

@david-heffernan I am running this code on a 32-bit system. I know The Magnification API is not supported under WOW64;. Which means 32-bit magnification application works on a 32-bit system and 64-bit magnification application works on a 64-bit system. Please stop commenting that magnification API doesn't work on WOW64 and try to execute this code on a 32-bit system.

As for your request the below image shows the configuration of my System.

enter image description here

Source: (StackOverflow)

JNA Keyboard Hook in Windows

I have put together a JNA code for installing keyboard hook in Windows (using the JNA examples). The code compiles and everything, and I get the hook installed (I get handle to the hook successfully), also I can uninstall the hook successfully. However, the callback never get called when I press any key on the keyboard. Here is my code (most of it are type definitions got from the JNA examples, go to the "main" directly for my part)

import com.sun.jna.IntegerType;
import com.sun.jna.Pointer;
import com.sun.jna.PointerType;
import com.sun.jna.Structure;
import com.sun.jna.FromNativeContext;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.StdCallLibrary.StdCallCallback;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Library;
import com.sun.jna.win32.W32APITypeMapper;
import com.sun.jna.win32.W32APIFunctionMapper;

import java.util.Map;
import java.util.HashMap;

public class HelloWorld {
    static Map UNICODE_OPTIONS = new HashMap() {
            put("type-mapper", W32APITypeMapper.UNICODE);
            put("function-mapper", W32APIFunctionMapper.UNICODE);

    public static class LONG_PTR extends IntegerType {
        public LONG_PTR() { this(0); }
        public LONG_PTR(long value) { super(Pointer.SIZE, value); }

    public static class UINT_PTR extends IntegerType {
        public UINT_PTR() { super(Pointer.SIZE); }
        public UINT_PTR(long value) { super(Pointer.SIZE, value); }
        public Pointer toPointer() { return Pointer.createConstant(longValue()); }

    public static class ULONG_PTR extends IntegerType {
        public ULONG_PTR() { this(0); }
        public ULONG_PTR(long value) { super(Pointer.SIZE, value); }

    public static class LRESULT extends LONG_PTR {
        public LRESULT() { this(0); }
        public LRESULT(long value) { super(value); }

    public static class WPARAM extends UINT_PTR {
        public WPARAM() { this(0); }
        public WPARAM(long value) { super(value); }

    public static class LPARAM extends LONG_PTR {
        public LPARAM() { this(0); }
        public LPARAM(long value) { super(value); }

    public static class KBDLLHOOKSTRUCT extends Structure {
        public int vkCode;
        public int scanCode;
        public int flags;
        public int time;
        public ULONG_PTR dwExtraInfo;

        { super.setPointer(Pointer.createConstant(-1)); }
        public void setPointer(Pointer p) {
            throw new UnsupportedOperationException("Immutable reference");

    public static class HANDLE extends PointerType {
        public Object fromNative(Object nativeValue, FromNativeContext context) {
            Object o = super.fromNative(nativeValue, context);
            if (INVALID_HANDLE_VALUE.equals(o))
                return INVALID_HANDLE_VALUE;
            return o;

    public static class HHOOK extends HANDLE { }
    public static class HINSTANCE extends HANDLE { }
    public static class HMODULE extends HINSTANCE { }

    public interface User32 extends StdCallLibrary  {
        User32 INSTANCE = (User32)Native.loadLibrary("user32", User32.class, UNICODE_OPTIONS);

        static final int WH_KEYBOARD_LL = 13;

        public static interface HOOKPROC extends StdCallCallback  {
            LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT lParam);

        HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, HMODULE hMod, int dwThreadId);
        LRESULT CallNextHookEx(HHOOK idHook, int nCode, WPARAM wParam, LPARAM lParam);
        LRESULT CallNextHookEx(HHOOK idHook, int nCode, WPARAM wParam, Pointer lParam);

        boolean UnhookWindowsHookEx(HHOOK idHook);

    public interface Kernel32 extends StdCallLibrary {
        Kernel32 INSTANCE = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class, UNICODE_OPTIONS);

        HMODULE GetModuleHandle(String name);

    public static HHOOK hHook;
    public static User32.HOOKPROC lpfn;
    public static volatile boolean quit = false;

    public static void main(String[] args) throws Exception {
        HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);

        lpfn = new User32.HOOKPROC() {
            public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT lParam) {
                quit = true;
                return User32.INSTANCE.CallNextHookEx(hHook, nCode, wParam, lParam.getPointer());

        hHook = User32.INSTANCE.SetWindowsHookEx(User32.WH_KEYBOARD_LL, lpfn, hMod, 0);

        if(hHook != null)
            System.out.println("Keyboard hooked, type anything to quit");

        while(!quit) {



I have done keyboard/mouse hooks several times using both C++ and C# in the past. This my first attempt with Java, and I just don't know whether I imported and mapped the library correctly. Any ideas?

Thank you.

Source: (StackOverflow)

Hunspell on Android

Does anyone successfully implemented Hunspell spell-checker on Android platform? Is it even possible? Did you try it? What about the results?

Thank you in advance.

Source: (StackOverflow)

Pinning a Java executable (with launch4j) to the Windows 7 taskbar

After spending half a day searching and trying, I'm finally giving up.

I have a java application of which I create a runnable jar (to include any other libs and just have a single jar file). With launch4j and the runnable jar I'm making an executable "MyApp.exe".

The executable ist working fine, but I want to pin it to my windows 7 taskbar. For now, I just have the taskbar entry "Close window".

After reading and implementing the following solutions with JNA

my Application displays it's "Application User Model ID" correctly in the gui (just for testing purpose).

BUT: my program is shown as "javaw.exe" in the Task Manager and I still can't pin it to the taskbar, even though I set the launch4j option "custom process name and XP style manifest".

Background information: I'm working with a windows 7 admin account and I don't want the app the require admin rights.

Anyways, if I start the app "as administrator" from the context menu and confirm the UAC message, I can now pin to the taskbar. BUT: even though I set the "Application User Model ID" properly, windows still wants to pin "javaw.exe", even though my program is now shown as "MyApp.exe" in the TaskManager.

I'm totaly confused. But I'm obviously not the only one, having these issues. => See the last comments to Gregory Pakosz answer in Using JNA to get/set application identifier

Final questions:

  1. Gregory Pakosz way with JNA to set the "Application User Model ID" ( ) is working for me. But still, windows recognizes my app as an instance of "javaw.exe". What else do I have to do?
  2. Did maybe some windows or java update break something here?
  3. Do I really have to run my app with elevated user rights? I really don't want to...
  4. Are there some more options in launch4j which I have to set?
  5. Do I have to use a manifest file in launch4j?

Source: (StackOverflow)

Disable Background drawing in JFrame in order to properly display Aero (DWM) effects

I'm having problems using the DWM functionality of Windows Vista/7 on Java windows. I want to make the background of my frame use the Aero style. The Windows API to do so is provide by the function DwmExtendFrameIntoClientArea in the dwmapi library. I've managed to call the procedure properly via JNA, and it does what it is supposed to do (You can see that for example when resizing the frame, before the next repaint you see the proper aero effects in the area not yet painted, see the attached image).

But somewhere (I can't figure out where) a background is painted over the Aero effect and the effect is lost.

What I have already tried:

  • Using a custom ContentPane with opacity set to false
  • Setting the opacity of the LayeredPane and the RootPane to false
  • Using a Frame instead of a JFrame
  • Set the background color of the JFrame/ContentPane to black/fully transparent
  • Use setLayersOpaque and a custom variant thereof, see first answer for more details

So far I could not succeed removing that background. Is it a limitation of AWT/Swing? How can I remove that background or use the Aero effect properly?

Your help is greatly appreciated.


Here a screenshot of a frame without any contents, having set the opacity of the RootPane, LayeredPane and ContentPane to false. I did it quickly while resizing. You see that the effect is properly applied to the area Java did not yet paint on. (As a new user I cannot post the image directly...)

Odd behavior

Upon further investigation I came across the following odd behavior. If the window size is 150x150 or below the contents are displayed transparently. This is very glitchy for normal window components. If you paint directly on the frame by overriding the paint() method everything is drawn semi-transparent. Additionally the coordinate system seems to be a little off, it appears as the zero point of the JFrame is set to the actual zero point of the window. Thus Swing tries to paint to areas where actually the window border is located, which then of course is not visible.

See this screenshot:

Example code

This is the code I use.

Requires jna.jar and platform.jar. Available from the JNA homepage.

import com.sun.jna.Function;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinNT.HRESULT;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;

public class AeroFrame extends JFrame {

    public AeroFrame() {

        JLabel label = new JLabel("Testlabel");




    private void enableAeroEffect() {
        NativeLibrary dwmapi = NativeLibrary.getInstance("dwmapi");
        HWND aeroFrameHWND = new HWND(Native.getWindowPointer(this));
        MARGINS margins = new MARGINS();
        margins.cxLeftWidth = -1;
        margins.cxRightWidth = -1;
        margins.cyBottomHeight = -1;
        margins.cyTopHeight = -1;
        //DwmExtendFrameIntoClientArea(HWND hWnd, MARGINS *pMarInset)
        Function extendFrameIntoClientArea = dwmapi.getFunction("DwmExtendFrameIntoClientArea");
        HRESULT result = (HRESULT) extendFrameIntoClientArea.invoke(HRESULT.class,
                new Object[] { aeroFrameHWND, margins});
            System.err.println("Call to DwmExtendFrameIntoClientArea failed.");

    public class MARGINS extends Structure implements Structure.ByReference {
            public int cxLeftWidth;
            public int cxRightWidth;
            public int cyTopHeight;
            public int cyBottomHeight;

    public static void main(String[] args) {
        try {

        } catch (Exception e) {
        new AeroFrame().setVisible(true);


Source: (StackOverflow)

Is there an equivalent to for JNA?

The site documents PInvoke signatures, user-defined types, and other information that you need to call unmanaged APIs from managed .NET code.

Is there a site that does the same for Java's JNA?

Source: (StackOverflow)

JNA library slower screenshot than robot class?

Since Robot.createScreenCaputure() method is slow, I decided to use native library. I searched and found this forum and find a specific code snipplet which uses JNA Library. It's an old version so that I rewrote the code:

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBufferUShort;
import java.awt.image.DirectColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

import com.sun.jna.Native;
import com.sun.jna.win32.W32APIOptions;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinGDI;

public class JNAScreenShot {

    public static BufferedImage getScreenshot(Rectangle bounds) {
        WinDef.HDC windowDC = GDI.GetDC(USER.GetDesktopWindow());
        WinDef.HBITMAP outputBitmap =
                bounds.width, bounds.height);
        try {
            WinDef.HDC blitDC = GDI.CreateCompatibleDC(windowDC);
            try {
                WinNT.HANDLE oldBitmap =
                        GDI.SelectObject(blitDC, outputBitmap);
                try {
                            0, 0, bounds.width, bounds.height,
                            bounds.x, bounds.y,
                } finally {
                    GDI.SelectObject(blitDC, oldBitmap);
                WinGDI.BITMAPINFO bi = new WinGDI.BITMAPINFO(40);
                bi.bmiHeader.biSize = 40;
                boolean ok =
                        GDI.GetDIBits(blitDC, outputBitmap, 0, bounds.height,
                        (byte[]) null, bi, WinGDI.DIB_RGB_COLORS);
                if (ok) {
                    WinGDI.BITMAPINFOHEADER bih = bi.bmiHeader;
                    bih.biHeight = -Math.abs(bih.biHeight);
                    bi.bmiHeader.biCompression = 0;
                    return bufferedImageFromBitmap(blitDC, outputBitmap, bi);
                } else {
                    return null;
            } finally {
        } finally {

    private static BufferedImage bufferedImageFromBitmap(WinDef.HDC blitDC,
            WinDef.HBITMAP outputBitmap,
            WinGDI.BITMAPINFO bi) {
        WinGDI.BITMAPINFOHEADER bih = bi.bmiHeader;
        int height = Math.abs(bih.biHeight);
        final ColorModel cm;
        final DataBuffer buffer;
        final WritableRaster raster;
        int strideBits =
                (bih.biWidth * bih.biBitCount);
        int strideBytesAligned =
                (((strideBits - 1) | 0x1F) + 1) >> 3;
        final int strideElementsAligned;
        switch (bih.biBitCount) {
            case 16:
                strideElementsAligned = strideBytesAligned / 2;
                cm = new DirectColorModel(16, 0x7C00, 0x3E0, 0x1F);
                buffer =
                        new DataBufferUShort(strideElementsAligned * height);
                raster =
                        bih.biWidth, height,
                        ((DirectColorModel) cm).getMasks(),
            case 32:
                strideElementsAligned = strideBytesAligned / 4;
                cm = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF);
                buffer =
                        new DataBufferInt(strideElementsAligned * height);
                raster =
                        bih.biWidth, height,
                        ((DirectColorModel) cm).getMasks(),
                throw new IllegalArgumentException("Unsupported bit count: " + bih.biBitCount);
        final boolean ok;
        switch (buffer.getDataType()) {
            case DataBuffer.TYPE_INT: {
                int[] pixels = ((DataBufferInt) buffer).getData();
                ok = GDI.GetDIBits(blitDC, outputBitmap, 0, raster.getHeight(), pixels, bi, 0);
            case DataBuffer.TYPE_USHORT: {
                short[] pixels = ((DataBufferUShort) buffer).getData();
                ok = GDI.GetDIBits(blitDC, outputBitmap, 0, raster.getHeight(), pixels, bi, 0);
                throw new AssertionError("Unexpected buffer element type: " + buffer.getDataType());
        if (ok) {
            return new BufferedImage(cm, raster, false, null);
        } else {
            return null;
    private static final User32 USER = User32.INSTANCE;
    private static final GDI32 GDI = GDI32.INSTANCE;

interface GDI32 extends com.sun.jna.platform.win32.GDI32,
        com.sun.jna.platform.win32.WinDef {

            (GDI32) Native.loadLibrary(GDI32.class);

    boolean BitBlt(HDC hdcDest, int nXDest, int nYDest,
            int nWidth, int nHeight, HDC hdcSrc,
            int nXSrc, int nYSrc, int dwRop);

    HDC GetDC(HWND hWnd);

    boolean GetDIBits(HDC dc, HBITMAP bmp, int startScan, int scanLines,
            byte[] pixels, BITMAPINFO bi, int usage);

    boolean GetDIBits(HDC dc, HBITMAP bmp, int startScan, int scanLines,
            short[] pixels, BITMAPINFO bi, int usage);

    boolean GetDIBits(HDC dc, HBITMAP bmp, int startScan, int scanLines,
            int[] pixels, BITMAPINFO bi, int usage);
    int SRCCOPY = 0xCC0020;

interface User32 extends com.sun.jna.platform.win32.User32 {

    User32 INSTANCE = (User32) Native.loadLibrary(User32.class, W32APIOptions.UNICODE_OPTIONS);

    com.sun.jna.platform.win32.WinDef.HWND GetDesktopWindow();

And a test code to see how much it faster faster than Robot Class:

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;

public class testClass {

    public static void main(String[] args) {

        BufferedImage bi = null, bj = null;
        Rectangle rect = new Rectangle(0, 0, 810, 384);
        long startTime, finishTime;

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            bi = JNAScreenShot.getScreenshot(rect);
        finishTime = System.currentTimeMillis();

        System.out.println("With JNA Library: " + (finishTime - startTime)/10);

        Robot robo = null;

        startTime = System.currentTimeMillis();
        try {
            robo = new Robot();
        } catch (AWTException a) {
        for (int i = 0; i < 10; i++) {
            bj = robo.createScreenCapture(rect);
        finishTime = System.currentTimeMillis();
        System.out.println("With Robot Class " + (finishTime - startTime)/10);

And the result is

With JNA Library: 77
With Robot Class 37

Guys, please someone explain why is that and how can I fasten it?

Source: (StackOverflow)

How do JavaCL and JogAmp JOCL compare?

JavaCL uses JNA, JOCL uses JNI instead, so I expect JavaCL to show better cross-platform compatibility, while JOCL should generally turn out to have better performance. JOCL gets tested alongside JOGL2, which should make it easy to use GL objects in CL and vice versa. JavaCL is able to generate its context from the current GL context. JavaCL is protected by the GPL, JOCL is distributed under the BSD license.

What else can be said about these two approaches? Are there any good comparisons out there?



Source: (StackOverflow)

How can I get system/hardware info via Java? [duplicate]

This question already has an answer here:

I need to get system and hardware info via Java Application.

I interests in:

  • Os details;
  • Processors count, names, processor load in percents;
  • Memory status (total/free);
  • Os process(threads) count and CPU/Memory usage for each of them;
  • Network statistic (for each interface);

I looking for Java library for this. Can anybody tell this?

Source: (StackOverflow)

How do I get maven to download the platform.jar from the JNA project

I have the following POM entry


When I build my project it downloads the following files:

  • jna-3.3.0.jar
  • jna-3.3.0.jar.sha1
  • jna-3.3.0.pom
  • jna-3.3.0.jar.sha1

If you visit the repository at you can see there are numerous other files. Why isn't Maven downloading those other files?

If you open the jna-3.3.0.pom you see

  <!-- fake out maven and install the binary artifact -->
            <!--<ant dir="." target="dist" />-->
            <attachArtifact file="dist/jna.jar" />
            <attachArtifact file="dist/platform.jar" classifier="platform" type="jar" />
            <attachArtifact file="dist/" classifier="sources" type="jar"/>

I suspect the issue has something to do with the comment in the pom "fake out maven and install the binary artifact".

Source: (StackOverflow)