1

我正在尝试制作一个应用程序,该应用程序在某个阶段存储由CTRL+复制的所有语句C,并操作将当前语句携带到特定语句的“缓冲区”

示例:用户按下CTRL+C复制 "Hello" ,如果他在任何文本区域/字段按下CTRL+ V,书面文字将是 "Hello" ,我希望书面语句是 "Test" 而不是 "Hello"

问题是:如何访问携带复制语句的缓冲区并使用 Java 操作其内容?

4

1 回答 1

1
  public static void main(String[] args) throws Exception
  {
    // Get a reference to the clipboard
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

    // Poll once per second for a minute
    for (int i = 0; i < 60; i++)
    {
      // Null is ok, because, according to the javadoc, the parameter is not currently used
      Transferable transferable = clipboard.getContents(null);

      // Ensure that the current contents can be expressed as a String
      if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor))
      {
        // Get clipboard contents and cast to String
        String data = (String) transferable.getTransferData(DataFlavor.stringFlavor);

        if (data.equals("Hello"))
        {
          // Change the contents of the clipboard
          StringSelection selection = new StringSelection("Test");
          clipboard.setContents(selection, selection);
        }
      }

      // Wait for a second before the next poll
      try
      {
        Thread.sleep(1000);
      }
      catch (InterruptedException e)
      {
        // no-op
      }
    }
  }

我为一些简单的可测试性/验证添加了轮询。它会在一分钟内每秒检查一次剪贴板。据我所知,没有办法进行基于事件的通知(除非你正在监听风味变化,但你不是),所以我认为你被轮询困住了。

于 2012-04-06T21:48:42.937 回答