Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Cursor;
- import java.awt.Point;
- import java.awt.Toolkit;
- import java.awt.image.BufferedImage;
- import javax.swing.ImageIcon;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import com.sun.jna.Pointer;
- /**
- * Taken from
- * https://stackoverflow.com/questions/739870/extract-cursor-image-in-java/740528
- */
- class CursorExtractor {
- private static void draw(BufferedImage image, int cursor,
- int diFlags) {
- int width = image.getWidth();
- int height = image.getHeight();
- User32 user32 = User32.INSTANCE;
- Gdi32 gdi32 = Gdi32.INSTANCE;
- Pointer hIcon = user32
- .LoadCursorW(Pointer.NULL, cursor);
- Pointer hdc = gdi32.CreateCompatibleDC(Pointer.NULL);
- Pointer bitmap = gdi32.CreateCompatibleBitmap(hdc,
- width, height);
- gdi32.SelectObject(hdc, bitmap);
- user32.DrawIconEx(hdc, 0, 0, hIcon, 0, 0, 0,
- Pointer.NULL, diFlags);
- for (int x = 0; x < width; x++) {
- for (int y = 0; y < width; y++) {
- int rgb = gdi32.GetPixel(hdc, x, y);
- image.setRGB(x, y, rgb);
- }
- }
- gdi32.DeleteObject(bitmap);
- gdi32.DeleteDC(hdc);
- }
- public static void main(String[] args) {
- BufferedImage image = getCursor(User32.IDC_ARROW);
- JLabel icon = new JLabel();
- icon.setIcon(new ImageIcon(image));
- JFrame frame = new JFrame();
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setContentPane(icon);
- frame.pack();
- frame.setVisible(true);
- Toolkit toolkit = Toolkit.getDefaultToolkit();
- Point pointerPos = new Point(1, 1);
- Cursor c = toolkit.createCustomCursor(image, pointerPos, "cursorname");
- frame.setCursor(c);
- }
- public static BufferedImage getCursor(int cursorType) {
- final int width = User32.INSTANCE.GetSystemMetrics(User32.SM_CXCURSOR);
- final int height = User32.INSTANCE.GetSystemMetrics(User32.SM_CYCURSOR);
- System.out.println(String.format("Cursor height: %d, Cursor weight: %d", height, width));
- BufferedImage image = new BufferedImage(width, height,
- BufferedImage.TYPE_INT_ARGB);
- draw(image, cursorType, User32.DI_NORMAL);
- BufferedImage mask = new BufferedImage(width, height,
- BufferedImage.TYPE_INT_RGB);
- draw(mask, cursorType, User32.DI_MASK);
- applyMask(image, mask);
- return image;
- }
- private static void applyMask(BufferedImage image,
- BufferedImage mask) {
- int width = image.getWidth();
- int height = image.getHeight();
- for (int x = 0; x < width; x++) {
- for (int y = 0; y < height; y++) {
- int masked = mask.getRGB(x, y);
- if ((masked & 0x00FFFFFF) == 0) {
- int rgb = image.getRGB(x, y);
- rgb = 0xFF000000 | rgb;
- image.setRGB(x, y, rgb);
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment