javalibgdxprintscreen

Making a Screenshot in LibGDX by Pressing the Prt Scr Button


By following this solution on Stack Overflow I have come up with the following Java class:

public final class Screenshot {

    private static byte[] pixels;
    private static Pixmap pixmap;

    public static void take() {
        pixels = ScreenUtils.getFrameBufferPixels(0, 0,
                Gdx.graphics.getBackBufferWidth(),
                Gdx.graphics.getBackBufferHeight(),
                true);

        pixmap = new Pixmap(Gdx.graphics.getBackBufferWidth(),
                Gdx.graphics.getBackBufferHeight(),
                Pixmap.Format.RGBA8888);

        BufferUtils.copy(pixels, 0, pixmap.getPixels(), pixels.length);
        PixmapIO.writePNG(Gdx.files.external("./screenshot_" + new Date().getTime() + ".png"), pixmap);

        pixmap.dispose();
        pixels = null;
    }
}

Calling Screenshot().take() will take the LibGDX render buffer and dump it in a PNG file. Exactly what I want.

My question is if there's a good way to 'capture' the print screen button. Is there a print screen keycode that I can use?


Solution

  • It seems that in LibGDX you cannot.

    The way you are checking the keyboard input is

        Gdx.input.isKeyPressed(key)
    

    where key is object of class Keys which does not includes prtscr button.

    What's more - the Keys objects are integers so I tried to find out what button code of prtsrc is by checking:

        uiStage.addListener(new ClickListener()
        {
            @Override
            public boolean keyDown(InputEvent event, int keycode)
            {
                System.out.println(keycode);
                return true;
            }
        });
    

    and I got 0 on my computer. I have checked what 0 is in Keys class by printing

        System.out.println(Input.Keys.toString(42));
    

    and the result was Unknown. I'm pretty surprised to be honest but it seems that LibGDX does not support PRINT_SCREEN button.

    Probably there is a way to ommit LibGDX mechanism and use the platform specific function to check if prtsrc was clicked (internet says that it's ASCII code is 44) but the answer for LibGDX itself seems to be - there is no way to do it.