dylanh724
dylanh724

Reputation: 1018

Read and Write to the clipboard

I have this snippet on Windows (VS2017 Community) on Unity 5.6:

public static void setClipboardStr(string str)
{
    try
    {
        if (Clipboard.ContainsText())
        {
            // ...doesn't matter if true or false - 
            // from here on, I can't copy+paste inside 
            // the game or outside until I close the app. 
            // If I had an error instead of try/catch or 
            // check if it contains text, the error will 
            // remain UNTIL I REBOOT (beyond the app closing).
        }
    }
    catch(Exception ex)
    {
        Debug.LogError(ex);
    }
}

Whenever I use Clipboard in any form, even when checking if it's text or not, it destroys the clipboard until I close the app. Now, is this a Unity bug? VS bug? Is there something I'm not understanding? What should I use, instead?

Upvotes: 16

Views: 8833

Answers (1)

Programmer
Programmer

Reputation: 125245

Clipboard.ContainsText is from the System.Windows.Forms namespace. These are not supported in Unity. One would be lucky to get it to compile and extremely luck to get work properly since Unity uses Mono. Also, this is not portable so don't use anything from this namespace in Unity.

What should I use, instead?

Write to clipboard:

GUIUtility.systemCopyBuffer = "Hello";

Read from clipboard:

string clipBoard = GUIUtility.systemCopyBuffer;

This should work. If not, you can implement your own clipboard API from scratch using their C++ API. You do have to do this for each platform.

Upvotes: 21

Related Questions