1 Vanara.Windows.Shell.NativeClipboard
David Hall edited this page 2020-08-23 19:51:36 -06:00
This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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(@"“Weve been here”", "<span style=\"color:#dcdcaa;\">“Weve been here”</span>", null /* Could be RTF text */);

// Optionally, you can push a single text format
using (var cb = new NativeClipboard())
   cb.SetText(@"“Weve 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)}");