如何获取当前 Java 程序窗口之外的选定文本?

huangapple go评论80阅读模式
英文:

How to get selected text outside of current java program window?

问题

我正在开发一个Java程序,它应该能够输出操作系统中其他应用程序(浏览器、文本编辑器、PDF阅读器等)中所选取的文本。

例如,我在Stack Overflow上选择了一些文本,然后运行我的Java程序,它应该输出我所选取的文本。

我在java.awt包中的Toolkit类中找到了getSystemSelection方法,但是我的程序输出的结果是null

我的程序如下所示 -

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

public class MyProg {

    public static void main(String args[])throws Exception
    {
        // 获取默认的Toolkit
        Toolkit T = Toolkit.getDefaultToolkit();
                    
        Clipboard c = T.getSystemSelection();

        System.out.println(c.getData(DataFlavor.stringFlavor));
    }
}

有人有任何建议吗?

英文:

I am working on a Java program which should output the selected text in other applications of the OS (browser, text-editor, pdf-reader etc.).

For example, I select some text on Stack-overflow and run my Java program, it should output the selected text.

I found the getSystemSelection method in the Toolkit class in java.awt package, but output of my program is null.

My program is as following -

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

public class MyProg {

        public static void main(String args[])throws Exception
        {
			
			// Get default Toolkit
			Toolkit T = Toolkit.getDefaultToolkit();
						
            Clipboard c = T.getSystemSelection();

            System.out.println(c.getData(DataFlavor.stringFlavor));
        }
    }

Does anyone has any suggestion?

答案1

得分: 1

我相信你提到的方法可以用于在你自己的应用程序内部访问所选文本。但是跨应用程序执行此操作的能力将受主机操作系统和其他应用程序的限制。在某些情况下,这可能是可能的,但肯定不是普遍适用的。因此,在Java中没有标准的方法来做到这一点。也许存在着一个不太常见的库,可以实现这个功能。可能需要使用类似C语言的语言编写一个JNI包装器,然后从Java中访问该包装器,并且该包装器需要针对每个支持的平台进行独特的实现。

一个简单的解决方法是要求用户将所选文本复制到剪贴板,此时在你的程序中从剪贴板读取内容将变得很简单,使用Toolkit.getDefaultToolkit().getSystemClipboard().getData()

英文:

I believe the method you mention will work for accessing the selected text anywhere within your own application. But the ability to do this across applications would be limited by the host operating system and the other application. In some cases it might be possible, but certainly not across the board. So there is not going to be a standard way to do this in Java. Perhaps an obscure library exists out there that does it. Likely it would require writing a JNI wrapper in a language like C and then accessing that from within Java, and that wrapper would need to have unique implementations for every supported platform.

A simple workaround would be to require that the user copy the selected text to the clipboard, at which point it would then be a simple matter to read from the clipboard in your program using Toolkit.getDefaultToolkit().getSystemClipboard().getData().

huangapple
  • 本文由 发表于 2020年5月5日 04:12:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/61600785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定