Skip to content

Vanara.Windows.Shell.NativeClipboard

David Hall edited this page Aug 24, 2020 · 1 revision

NativeClipboard

Pushing text to the Clipboard

One function I often need is one that will push text onto the clipboard in multiple formats. There are few ways to do that with this class:

// This function will push text in Unicode, Html, RTF (optional) and will set the Locale value to the current culture.
using (var cb = new NativeClipboard())
   cb.SetText(@"“We’ve been here”", "<span style=\"color:#dcdcaa;\">“We’ve been here”</span>", null /* Could be RTF text */);

// Optionally, you can push a single text format
using (var cb = new NativeClipboard())
   cb.SetText(@"“We’ve been here”", TextDataFormat.UnicodeText);

Pushing binary data to the Clipboard

// Get a custom id or use one of the exiting
var fmtId = DataFormats.GetFormat("MyBinData").Id;

// At the heart of all things is just pushing a byte stream
using (var cb = new NativeClipboard())
   cb.SetBinaryData(fmtId, new byte[] { 12, 24, 48, 96, 8, 16, 32, 64, 128 });

// Or, push a blittable structure
using (var cb = new NativeClipboard())
   cb.SetData(fmtId, new RECT(0, 0, 10, 100));

// Or, push an array of blittable structures
using (var cb = new NativeClipboard())
   cb.SetData(fmtId, new[] { new RECT(0, 0, 10, 100), new RECT(1, 1, 5, 10), new RECT(2, 2, 15, 20) });

Getting list of all available formats on the clipboard

using (var cb = new NativeClipboard())
{
   if (cb.EnumAvailableFormats().Any(f => f.Name == DataFormats.Dib))
   {
      // Do something
   }
}

// Or, look at just a single one
using (var cb = new NativeClipboard())
   Console.WriteLine($"Dib avail? {cs.IsFormatAvailable(DataFormats.Dib)}");