Stacker
Stacker

Reputation: 8237

Retrieving copied text from clipboard

I'm trying to retrieve text copied to the clipboard, but text never gets retrieved.

I am using this piece of code:

if (Clipboard.ContainsText())
{                              
    text = Clipboard.GetText();
}

Now this condition never returns true, which means clipboard never contains any text, although I copied several pieces of text to the clipboard.

I also tried this code too and it's the same:

   IDataObject iData = Clipboard.GetDataObject();

   if (iData != null && iData.GetDataPresent(DataFormats.Text))
   {
         text = (String)iData.GetData(DataFormats.Text);
   }

Upvotes: 0

Views: 1182

Answers (2)

Markus
Markus

Reputation: 438

Or you can use;

    static string clipHTML { get; set; } 

    public yourclass()
    {

    clipHTML = Clipboard.GetText(TextDataFormat.Html);

    }

Depending on what .NET Framework you are using you might head warning below.

DataFormats.Html specification states it's encoded in UTF-8. But there's a bug in .NET 4 Framework and lower, and it actually reads as UTF-8 as Windows-1252.

You get allot of wrong encodings, which leading to funny/bad characters such as 'Å','‹','Å’','Ž','Å¡','Å“','ž','Ÿ','Â','¡','¢','£','¤','Â¥','¦','§','¨','©'

For example '€' is wrongly encoded as '€' in Windows-1252.

Full explanation here at this dedicated website Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters

But by using the conversions tables you will not loose any UTF-8 characters. You can get the original pristine UTF-8 characters from DataFormats.Html. (Note: Ppm solution defaults to ASCII for this & you loose information)

Soln: Create a translation dictionary and search and replace.

Upvotes: 1

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You specify your format in your Contains, here an sample with html data

use ContainsData and GetText

     bool IsHTMLDataOnClipboard = Clipboard.ContainsData(DataFormats.Html);
     string htmlData;
     if(IsHTMLDataOnClipboard)
     {
         htmlData = Clipboard.GetText(TextDataFormat.Html);
     }

Upvotes: 1

Related Questions