【问题标题】:Buffer carrying stored statement using Ctrl+C使用 Ctrl+C 携带存储语句的缓冲区
【发布时间】:2012-04-20 10:06:34
【问题描述】:

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

示例:用户按下 CTRL + C 复制“Hello”,如果他按下 CTRL + V 在任何文本区域/字段中,书面文字都是“Hello”,我希望书面陈述是“Test”而不是“Hello”

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

【问题讨论】:

  • 所以你想完全改变操作系统剪贴板的内容?不,谢谢。
  • Copying to Clipboard in Java 的可能重复项
  • @BlueRaja-DannyPflughoeft 是的,这是我真正想要的,但无法用好的陈述来表达,谢谢

标签: java buffer copy-paste


【解决方案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
      }
    }
  }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多