Search in sources :

Example 61 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class GDI32Util method getScreenshot.

/**
	 * Takes a screenshot of the given window
	 * 
	 * @param target
	 *            The window to target
	 * @return the window captured as a screenshot, or null if the BufferedImage doesn't construct properly
	 * @throws IllegalStateException
	 *             if the rectangle from GetWindowRect has a width and/or height
	 *             of 0. <br>
	 *             if the device context acquired from the original HWND doesn't
	 *             release properly
	 */
public static BufferedImage getScreenshot(HWND target) {
    RECT rect = new RECT();
    if (!User32.INSTANCE.GetWindowRect(target, rect)) {
        throw new Win32Exception(Native.getLastError());
    }
    Rectangle jRectangle = rect.toRectangle();
    int windowWidth = jRectangle.width;
    int windowHeight = jRectangle.height;
    if (windowWidth == 0 || windowHeight == 0) {
        throw new IllegalStateException("Window width and/or height were 0 even though GetWindowRect did not appear to fail.");
    }
    HDC hdcTarget = User32.INSTANCE.GetDC(target);
    if (hdcTarget == null) {
        throw new Win32Exception(Native.getLastError());
    }
    Win32Exception we = null;
    // device context used for drawing
    HDC hdcTargetMem = null;
    // handle to the bitmap to be drawn to
    HBITMAP hBitmap = null;
    // original display surface associated with the device context
    HANDLE hOriginal = null;
    // final java image structure we're returning.
    BufferedImage image = null;
    try {
        hdcTargetMem = GDI32.INSTANCE.CreateCompatibleDC(hdcTarget);
        if (hdcTargetMem == null) {
            throw new Win32Exception(Native.getLastError());
        }
        hBitmap = GDI32.INSTANCE.CreateCompatibleBitmap(hdcTarget, windowWidth, windowHeight);
        if (hBitmap == null) {
            throw new Win32Exception(Native.getLastError());
        }
        hOriginal = GDI32.INSTANCE.SelectObject(hdcTargetMem, hBitmap);
        if (hOriginal == null) {
            throw new Win32Exception(Native.getLastError());
        }
        // draw to the bitmap
        if (!GDI32.INSTANCE.BitBlt(hdcTargetMem, 0, 0, windowWidth, windowHeight, hdcTarget, 0, 0, GDI32.SRCCOPY)) {
            throw new Win32Exception(Native.getLastError());
        }
        BITMAPINFO bmi = new BITMAPINFO();
        bmi.bmiHeader.biWidth = windowWidth;
        bmi.bmiHeader.biHeight = -windowHeight;
        bmi.bmiHeader.biPlanes = 1;
        bmi.bmiHeader.biBitCount = 32;
        bmi.bmiHeader.biCompression = WinGDI.BI_RGB;
        Memory buffer = new Memory(windowWidth * windowHeight * 4);
        int resultOfDrawing = GDI32.INSTANCE.GetDIBits(hdcTarget, hBitmap, 0, windowHeight, buffer, bmi, WinGDI.DIB_RGB_COLORS);
        if (resultOfDrawing == 0 || resultOfDrawing == WinError.ERROR_INVALID_PARAMETER) {
            throw new Win32Exception(Native.getLastError());
        }
        int bufferSize = windowWidth * windowHeight;
        DataBuffer dataBuffer = new DataBufferInt(buffer.getIntArray(0, bufferSize), bufferSize);
        WritableRaster raster = Raster.createPackedRaster(dataBuffer, windowWidth, windowHeight, windowWidth, SCREENSHOT_BAND_MASKS, null);
        image = new BufferedImage(SCREENSHOT_COLOR_MODEL, raster, false, null);
    } catch (Win32Exception e) {
        we = e;
    } finally {
        if (hOriginal != null) {
            // per MSDN, set the display surface back when done drawing
            HANDLE result = GDI32.INSTANCE.SelectObject(hdcTargetMem, hOriginal);
            // failure modes are null or equal to HGDI_ERROR
            if (result == null || WinGDI.HGDI_ERROR.equals(result)) {
                Win32Exception ex = new Win32Exception(Native.getLastError());
                if (we != null) {
                    ex.addSuppressed(we);
                }
                we = ex;
            }
        }
        if (hBitmap != null) {
            if (!GDI32.INSTANCE.DeleteObject(hBitmap)) {
                Win32Exception ex = new Win32Exception(Native.getLastError());
                if (we != null) {
                    ex.addSuppressed(we);
                }
                we = ex;
            }
        }
        if (hdcTargetMem != null) {
            // get rid of the device context when done
            if (!GDI32.INSTANCE.DeleteDC(hdcTargetMem)) {
                Win32Exception ex = new Win32Exception(Native.getLastError());
                if (we != null) {
                    ex.addSuppressed(we);
                }
                we = ex;
            }
        }
        if (hdcTarget != null) {
            if (0 == User32.INSTANCE.ReleaseDC(target, hdcTarget)) {
                throw new IllegalStateException("Device context did not release properly.");
            }
        }
    }
    if (we != null) {
        throw we;
    }
    return image;
}
Also used : RECT(com.sun.jna.platform.win32.WinDef.RECT) HDC(com.sun.jna.platform.win32.WinDef.HDC) Memory(com.sun.jna.Memory) Rectangle(java.awt.Rectangle) DataBufferInt(java.awt.image.DataBufferInt) BufferedImage(java.awt.image.BufferedImage) Win32Exception(com.sun.jna.platform.win32.Win32Exception) WritableRaster(java.awt.image.WritableRaster) BITMAPINFO(com.sun.jna.platform.win32.WinGDI.BITMAPINFO) HBITMAP(com.sun.jna.platform.win32.WinDef.HBITMAP) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) DataBuffer(java.awt.image.DataBuffer)

Example 62 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class Kernel32Util method getFileType.

/**
     * Retrieves the result of GetFileType, provided the file exists.
     * @param fileName file name
     * @return file type
     * @throws FileNotFoundException if file not found
     */
public static int getFileType(String fileName) throws FileNotFoundException {
    File f = new File(fileName);
    if (!f.exists()) {
        throw new FileNotFoundException(fileName);
    }
    HANDLE hFile = null;
    Win32Exception err = null;
    try {
        hFile = Kernel32.INSTANCE.CreateFile(fileName, WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, new HANDLEByReference().getValue());
        if (WinBase.INVALID_HANDLE_VALUE.equals(hFile)) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        int type = Kernel32.INSTANCE.GetFileType(hFile);
        switch(type) {
            case WinNT.FILE_TYPE_UNKNOWN:
                int rc = Kernel32.INSTANCE.GetLastError();
                switch(rc) {
                    case WinError.NO_ERROR:
                        break;
                    default:
                        throw new Win32Exception(rc);
                }
            default:
                return type;
        }
    } catch (Win32Exception e) {
        err = e;
        // re-throw so finally block executed
        throw err;
    } finally {
        try {
            closeHandle(hFile);
        } catch (Win32Exception e) {
            if (err == null) {
                err = e;
            } else {
                err.addSuppressed(e);
            }
        }
        if (err != null) {
            throw err;
        }
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) HANDLEByReference(com.sun.jna.platform.win32.WinNT.HANDLEByReference) File(java.io.File) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE)

Example 63 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class Kernel32Util method getResource.

/**
     * Gets the specified resource out of the specified executable file
     *
     * @param path
     *            The path to the executable file
     * @param type
     *            The type of the resource (either a type name or type ID is
     *            allowed)
     * @param name
     *            The name or ID of the resource
     * @return The resource bytes, or null if no such resource exists.
     * @throws IllegalStateException if the call to LockResource fails
     */
public static byte[] getResource(String path, String type, String name) {
    HMODULE target = Kernel32.INSTANCE.LoadLibraryEx(path, null, Kernel32.LOAD_LIBRARY_AS_DATAFILE);
    if (target == null) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    Win32Exception err = null;
    Pointer start = null;
    int length = 0;
    byte[] results = null;
    try {
        Pointer t = null;
        try {
            t = new Pointer(Long.parseLong(type));
        } catch (NumberFormatException e) {
            t = new Memory(Native.WCHAR_SIZE * (type.length() + 1));
            t.setWideString(0, type);
        }
        Pointer n = null;
        try {
            n = new Pointer(Long.parseLong(name));
        } catch (NumberFormatException e) {
            n = new Memory(Native.WCHAR_SIZE * (name.length() + 1));
            n.setWideString(0, name);
        }
        HRSRC hrsrc = Kernel32.INSTANCE.FindResource(target, n, t);
        if (hrsrc == null) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        // according to MSDN, on 32 bit Windows or newer, calling FreeResource() is not necessary - and in fact does nothing but return false.
        HANDLE loaded = Kernel32.INSTANCE.LoadResource(target, hrsrc);
        if (loaded == null) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        length = Kernel32.INSTANCE.SizeofResource(target, hrsrc);
        if (length == 0) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        // MSDN: It is not necessary to unlock resources because the system automatically deletes them when the process that created them terminates.
        // MSDN does not say that LockResource sets GetLastError
        start = Kernel32.INSTANCE.LockResource(loaded);
        if (start == null) {
            throw new IllegalStateException("LockResource returned null.");
        }
        // have to capture it into a byte array before you free the library, otherwise bad things happen.
        results = start.getByteArray(0, length);
    } catch (Win32Exception we) {
        err = we;
    } finally {
        // from what I can tell on MSDN, the only thing that needs cleanup on this is the HMODULE from LoadLibrary
        if (target != null) {
            if (!Kernel32.INSTANCE.FreeLibrary(target)) {
                Win32Exception we = new Win32Exception(Kernel32.INSTANCE.GetLastError());
                if (err != null) {
                    we.addSuppressed(err);
                }
                throw we;
            }
        }
    }
    if (err != null) {
        throw err;
    }
    return results;
}
Also used : Memory(com.sun.jna.Memory) Pointer(com.sun.jna.Pointer) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE)

Example 64 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class Netapi32Util method getGlobalGroups.

/**
     * Get the names of global groups on a computer.
     * @param serverName Name of the computer.
     * @return An array of group names.
     */
public static Group[] getGlobalGroups(String serverName) {
    PointerByReference bufptr = new PointerByReference();
    IntByReference entriesRead = new IntByReference();
    IntByReference totalEntries = new IntByReference();
    try {
        int rc = Netapi32.INSTANCE.NetGroupEnum(serverName, 1, bufptr, LMCons.MAX_PREFERRED_LENGTH, entriesRead, totalEntries, null);
        if (LMErr.NERR_Success != rc || bufptr.getValue() == Pointer.NULL) {
            throw new Win32Exception(rc);
        }
        LMAccess.GROUP_INFO_1 group = new LMAccess.GROUP_INFO_1(bufptr.getValue());
        LMAccess.GROUP_INFO_1[] groups = (LMAccess.GROUP_INFO_1[]) group.toArray(entriesRead.getValue());
        ArrayList<LocalGroup> result = new ArrayList<LocalGroup>();
        for (LMAccess.GROUP_INFO_1 lgpi : groups) {
            LocalGroup lgp = new LocalGroup();
            if (lgpi.grpi1_name != null) {
                lgp.name = lgpi.grpi1_name.toString();
            }
            if (lgpi.grpi1_comment != null) {
                lgp.comment = lgpi.grpi1_comment.toString();
            }
            result.add(lgp);
        }
        return result.toArray(new LocalGroup[0]);
    } finally {
        if (bufptr.getValue() != Pointer.NULL) {
            int rc = Netapi32.INSTANCE.NetApiBufferFree(bufptr.getValue());
            if (LMErr.NERR_Success != rc) {
                throw new Win32Exception(rc);
            }
        }
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) LOCALGROUP_INFO_1(com.sun.jna.platform.win32.LMAccess.LOCALGROUP_INFO_1) PointerByReference(com.sun.jna.ptr.PointerByReference) ArrayList(java.util.ArrayList)

Example 65 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class Crypt32Util method cryptUnprotectData.

/**
     * Unprotect a blob of data.
     * @param data
     *  Data to unprotect.
     * @param entropy
     *  Optional entropy.
     * @param flags
     *  Optional flags.
     * @param prompt
     *  Optional prompt structure.
     * @return
     *  Unprotected blob of data.
     */
public static byte[] cryptUnprotectData(byte[] data, byte[] entropy, int flags, CRYPTPROTECT_PROMPTSTRUCT prompt) {
    DATA_BLOB pDataIn = new DATA_BLOB(data);
    DATA_BLOB pDataUnprotected = new DATA_BLOB();
    DATA_BLOB pEntropy = (entropy == null) ? null : new DATA_BLOB(entropy);
    PointerByReference pDescription = new PointerByReference();
    Win32Exception err = null;
    byte[] unProtectedData = null;
    try {
        if (!Crypt32.INSTANCE.CryptUnprotectData(pDataIn, pDescription, pEntropy, null, prompt, flags, pDataUnprotected)) {
            err = new Win32Exception(Kernel32.INSTANCE.GetLastError());
        } else {
            unProtectedData = pDataUnprotected.getData();
        }
    } finally {
        if (pDataUnprotected.pbData != null) {
            try {
                Kernel32Util.freeLocalMemory(pDataUnprotected.pbData);
            } catch (Win32Exception e) {
                if (err == null) {
                    err = e;
                } else {
                    err.addSuppressed(e);
                }
            }
        }
        if (pDescription.getValue() != null) {
            try {
                Kernel32Util.freeLocalMemory(pDescription.getValue());
            } catch (Win32Exception e) {
                if (err == null) {
                    err = e;
                } else {
                    err.addSuppressed(e);
                }
            }
        }
    }
    if (err != null) {
        throw err;
    }
    return unProtectedData;
}
Also used : PointerByReference(com.sun.jna.ptr.PointerByReference) DATA_BLOB(com.sun.jna.platform.win32.WinCrypt.DATA_BLOB)

Aggregations

IntByReference (com.sun.jna.ptr.IntByReference)35 HKEYByReference (com.sun.jna.platform.win32.WinReg.HKEYByReference)18 HANDLE (com.sun.jna.platform.win32.WinNT.HANDLE)17 Memory (com.sun.jna.Memory)15 PointerByReference (com.sun.jna.ptr.PointerByReference)11 ArrayList (java.util.ArrayList)11 EVT_HANDLE (com.sun.jna.platform.win32.Winevt.EVT_HANDLE)7 Pointer (com.sun.jna.Pointer)6 File (java.io.File)6 HANDLEByReference (com.sun.jna.platform.win32.WinNT.HANDLEByReference)5 Test (org.junit.Test)5 DWORD (com.sun.jna.platform.win32.WinDef.DWORD)4 HRESULT (com.sun.jna.platform.win32.WinNT.HRESULT)4 PSID (com.sun.jna.platform.win32.WinNT.PSID)4 Win32Exception (com.sun.jna.platform.win32.Win32Exception)3 HMODULE (com.sun.jna.platform.win32.WinDef.HMODULE)3 LOCALGROUP_INFO_1 (com.sun.jna.platform.win32.LMAccess.LOCALGROUP_INFO_1)2 LOCALGROUP_USERS_INFO_0 (com.sun.jna.platform.win32.LMAccess.LOCALGROUP_USERS_INFO_0)2 DATA_BLOB (com.sun.jna.platform.win32.WinCrypt.DATA_BLOB)2 DWORDByReference (com.sun.jna.platform.win32.WinDef.DWORDByReference)2