Getting binary data directly off the windows clipboard

后端 未结 1 386
执笔经年
执笔经年 2021-01-11 22:38

I\'ve been beating my head against the desk for about an hour now just trying to find some way of getting say... an array of bytes off the clipboard. Instead, all I can see

1条回答
  •  一生所求
    2021-01-11 23:26

    Awt Clipboard and MIME types

    InsideClipboard shows that the content's MIME type is application/spark editor

    You should be able to create a MIME type DataFlavor by using the constructor DataFlavor(String mimeType, String humanReadableFormat) in which case the class representation will be an InputStream from which you can extract bytes in a classic manner...

    However, this clipboard implementation is very strict on the mime type definition and you cannot use spaces in the format id, which is too bad because your editor seems to put a space there :(

    Possible solution, if you have access to JavaFX

    JavaFX's clipboard management is more lenient and tolerates various "Format Names" (as InsideClipboard calls them) in the clipboard, not just no-space type/subtype mime formats like in awt.

    For example, using LibreOffice Draw 4.2 and copying a Rectangle shape, awt only sees a application/x-java-rawimage format whereas JavaFX sees all the same formats as InsideClipboard :

    [application/x-java-rawimage], [PNG], [Star Object Descriptor (XML)], [cf3], [Windows Bitmap], [GDIMetaFile], [cf17], [Star Embed Source (XML)], [Drawing Format]

    You can then get the raw data from the JavaFX clipboard in a java.nio.ByteBuffer

    //with awt
    DataFlavor[] availableDataFlavors = Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors();
    System.out.println("Awt detected flavors : "+availableDataFlavors.length);
    for (DataFlavor f : availableDataFlavors) {
        System.out.println(f);
    }
    
    //with JavaFX (called from JavaFX thread, eg start method in a javaFX Application
    Set contentTypes = Clipboard.getSystemClipboard().getContentTypes();
    System.out.println("JavaFX detected flavors : " + contentTypes.size());
    for (DataFormat s : contentTypes) {
            System.out.println(s);
    }
    
    //let's attempt to extract bytes from the clipboard containing data from the game editor
    // (note : some types will be automatically mapped to Java classes, and unknown types to a ByteBuffer)
    // another reproducable example is type "Drawing Format" with a Rectangle shape copied from LibreOffice Draw 4.2
    DataFormat df = DataFormat.lookupMimeType("application/spark editor");
    if (df != null) {
        Object content = Clipboard.getSystemClipboard().getContent(df);
        if (content instanceof ByteBuffer) {
            ByteBuffer buffer = (ByteBuffer) content;
            System.err.println(new String(buffer.array(), "UTF-8"));
        } else
            System.err.println(content);
    }
    

    0 讨论(0)
提交回复
热议问题