CopyText / TextCopy

A cross platform package to copy text to and from the clipboard.
MIT License
513 stars 41 forks source link

TextCopy

Build status NuGet Status

A cross platform package to copy text to and from the clipboard.

See Milestones for release notes.

NuGet package

https://nuget.org/packages/TextCopy/

Usage

SetTextAsync

await ClipboardService.SetTextAsync("Text to place in clipboard");

snippet source | anchor

SetText

ClipboardService.SetText("Text to place in clipboard");

snippet source | anchor

GetTextAsync

var text = await ClipboardService.GetTextAsync();

snippet source | anchor

GetText

var text = ClipboardService.GetText();

snippet source | anchor

Clearing The Clipboard

ClipboardService.SetText("");

snippet source | anchor

await ClipboardService.SetTextAsync("");

snippet source | anchor

Instance API

In addition to the above static API, there is an instance API exposed:

Clipboard clipboard = new();
clipboard.SetText("Text to place in clipboard");

snippet source | anchor

Dependency Injection

An instance of Clipboard can be injected into IServiceCollection:

serviceCollection.InjectClipboard();

snippet source | anchor

The instance should be injected by using IClipboard.

There is also a InjectMockClipboard that injects an instance of MockClipboard with all methods stubbed out.

Supported on

Blazor WebAssembly

Due to the dependency on JSInterop the static ClipboardService is not supported on Blazor.

Instead inject an IClipboard:

var builder = WebAssemblyHostBuilder.CreateDefault();
var serviceCollection = builder.Services;
serviceCollection.InjectClipboard();
builder.RootComponents.Add<App>("app");

snippet source | anchor

Then consume it:

public partial class IndexModel :
    ComponentBase
{
    [Inject]
    public IClipboard Clipboard { get; set; }

    public string Content { get; set; }

    public Task CopyTextToClipboard() =>
        Clipboard.SetTextAsync(Content);

    public async Task ReadTextFromClipboard() =>
        Content = await Clipboard.GetTextAsync();
}

snippet source | anchor

Blazor support requires the browser APIs clipboard.readText and clipboard.writeText.

Linux

Linux uses xsel to access the clipboard. As such it needs to be installed and callable.

Icon

Clone designed by Wes Breazell from The Noun Project.