Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 930
dylanh724 Avatar asked Jul 29 '17 07:07

dylanh724


People also ask

What is clipboard write?

write() The Clipboard method write() writes arbitrary data, such as images, to the clipboard. This can be used to implement cut and copy functionality. The "clipboard-write" permission of the Permissions API, is granted automatically to pages when they are in the active tab.

How do I read clipboard?

Look for a clipboard icon in the top toolbar. This will open the clipboard, and you'll see the recently copied item at the front of the list. Simply tap any of the options in the clipboard to paste it into the text field.

How do I put text in my clipboard?

Select the text or graphics you want to copy, and press Ctrl+C. Each selection appears in the Clipboard, with the latest at the top. Optionally, repeat step 2 until you've copied all the items you want to use.

Where is the clipboard in Firefox?

In order to access stored clipboard items, please open toolbar popup or right-click on an editable area and then choose clipboard manager in the right-click. Then, click on a desired clipboard item; and it will be inserted to the editable filed.


1 Answers

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.

like image 144
Programmer Avatar answered Nov 12 '22 00:11

Programmer