Wakko
Wakko

Reputation: 95

How can I take control of windows copy paste events?

I need to make a file copier in java.

I want to know how to be acknowledged of an event that occurred in the operating systems file system and how to take control over it.

Upvotes: 1

Views: 3819

Answers (1)

Rahul Agrawal
Rahul Agrawal

Reputation: 8971

Write a thread which continuously perform clipboard data check using below code as

// If a string is on the system clipboard, this method returns it;
// otherwise it returns null.
public static String getClipboard() {
    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

    try {
        if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            String text = (String)t.getTransferData(DataFlavor.stringFlavor);
            return text;
        }
    } catch (UnsupportedFlavorException e) {
    } catch (IOException e) {
    }
    return null;
}

// This method writes a string to the system clipboard.
// otherwise it returns null.
public static void setClipboard(String str) {
    StringSelection ss = new StringSelection(str);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
}

For more details refer below classes

 java.awt.datatransfer.Clipboard;
 java.awt.datatransfer.ClipboardOwner;
 java.awt.datatransfer.Transferable;
 java.awt.datatransfer.StringSelection;
 java.awt.datatransfer.DataFlavor;

Below is Listener example

import java.awt.*;  
import java.awt.datatransfer.*;  

class BoardListener extends Thread implements ClipboardOwner {  
  Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();  

  public void run() {  
    Transferable trans = sysClip.getContents(this);  
    regainOwnership(trans);  
    System.out.println("Listening to board...");  
    while(true) {}  
  }  

  public void lostOwnership(Clipboard c, Transferable t) {  
    Transferable contents = sysClip.getContents(this); //EXCEPTION  
    processContents(contents);  
    regainOwnership(contents);  
  }  

  void processContents(Transferable t) {  
    System.out.println("Processing: " + t);  
  }  

  void regainOwnership(Transferable t) {  
    sysClip.setContents(t, this);  
  }  

  public static void main(String[] args) {  
    BoardListener b = new BoardListener();  
    b.start();  
  }  
}  

Upvotes: 2

Related Questions