Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Text from Clipboard

Tags:

c#

unity3d

I am trying to read the text in the clipboard in C# in Unity and then set it to a variable.

I have seen this article however it doesn't seem to work in Unity: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.clipboard.gettext

I just want to be able to read plain text. No images or anything. I have also found a few other articles on this however none of the code works in Unity.

like image 612
Andrew Avatar asked Mar 08 '16 12:03

Andrew


People also ask

How do I read clipboard?

To get to your clipboard history at any time, press Windows logo key + V. From the clipboard history, you can paste and pin frequently used items by choosing an individual item from your clipboard menu.

How do I find clipboard data in Chrome?

This hidden feature is available as a flag. To find it, open a new tab, paste chrome://flags into Chrome's Omnibox and then press the Enter key. Search for “Clipboard” in the search box.

What does Navigator clipboard writeText do?

writeText() The Clipboard interface's writeText() property writes the specified text string to the system clipboard. Text may be read back using either read() or readText() .

Can I use Navigator clipboard writeText?

writeText() work on all browsers, navigator. clipboard. read() and navigator.


1 Answers

I made a quick example to show how to use the Clipboard class from the System.Windows.Forms namespace. It turns out, that the method needed the [STAThread] method attribute to work. I don't know if that is possible to use in a Unity3D C# script.

[STAThread]
static void Main(string[] args)
{
    if (Clipboard.ContainsText(TextDataFormat.Text))
    {
        string clipboardText = Clipboard.GetText(TextDataFormat.Text);
        // Do whatever you need to do with clipboardText
    }
}

To learn more about what the attribute is used for, have a look at this question (and more importantly, its answers): What does [STAThread] do?

EDIT:

I did a little bit of digging, and it looks like Unity3D has a wrapper for the System Clipboard. I haven't tried it yet, but it looks like it should work across different operating systems and not just for Windows: GUIUtility.systemCopyBuffer

like image 50
Lars Kristensen Avatar answered Sep 29 '22 11:09

Lars Kristensen