Andrew
Andrew

Reputation: 367

Read Text from Clipboard

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://learn.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.

Upvotes: 11

Views: 34317

Answers (1)

Lars Kristensen
Lars Kristensen

Reputation: 1495

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

Upvotes: 24

Related Questions