Copy/Paste cross platform

I am looking for a way to copy/paste to and from the clipboard. I know with windows I can use: System.Windows.Forms.Clipboard.SetText(""). But what options do I have for Android, ios, linux etc. Is it something simple where I can use preprocessor directives like below? Or is there a simpler catch all solution?

#if Windows
System.Windows.Forms.Clipboard.SetText(textbox1.text);
#end if

#if Android
…???
#end if

Not really a MonoGame thing, but you can achieve this with a call to an Android thing. I did a quick search and found this…

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
clipboard.setText("Text to copy");
clipboard.getText();

Reference:

Also, just as a quick point of advice, putting those “#if Windows” and “#if Android” statements all of your code can often make things a little messy. If you’re interested in another option, you might try dependency injection. Create an interface that defines the behaviour you want, then create classes that implement the interface for various platforms. You can inject the appropriate dependency depending on which platform you’re in.

For example…

public interface IClipboardManager
{
  void SetText(string text);
}

public class WindowsClipboardManager : IClipboardManager
{
  public void SetText(string text)
  {
    System.Windows.Forms.Clipboard.SetText(text);
  }
}

public class AndroidClipboardManager : IClipboardManager
{
  ClipboardManager _wrappedManager;
  public AndroidClipboardManager(ClipboardManager managerToWrap)
  {
    _wrappedManager = managerToWrap ?? throw new ArgumentNullException();
  }

  public void SetText(string text)
  {
    _wrappedManager.setText(text);
  }
}

You can then instantiate the dependency you need in the appropriate place (ie, Program.cs or Activity1.cs) and pass it to your game, or store it in some global dependency container if you’re so inclined.

Either way, good luck! :slight_smile:

1 Like