Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string from dataPackageView.GetDataAsync()

I'm trying to get non-standard-format data from the clipboard using DataPackageView.GetDataAsync. I am stumped on converting the returned system.__ComObject to a string.

Here is the code:

var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();

if (dataPackageView.Contains("FileName"))
{
  var data = await dataPackageView.GetDataAsync("FileName");
  // How to convert data to string?

}

I am looking for a solution that will work with any non-standard clipboard format. "FileName" is an easily testable format as you can put it on the clipboard by copying a file in Windows Explorer.

In C++/Win32, I can get the clipboard data as follows:

OpenClipboard(nullptr);
UINT clipboarFormat = RegisterClipboardFormat(L"FileName");
HANDLE hData = GetClipboardData(clipboarFormat);
char * pszText = static_cast<char*>(GlobalLock(hData));
GlobalUnlock(hData);
CloseClipboard();

In C++, the clipboard data is just an array of bytes. It must be possible to get the same array of bytes in C#, but I have no clue on unwrapping/converting the system.__ComObject

Edit: Rephrasing the question:

How do I get a string or array of byes out of the system.__ComObject returned by dataPackageView.GetDataAsync(someFormat), where someFormat is an arbitrary clipboard format created by another application?

It is very clear to me how to get the data. The difficult part is using the data that is returned.

The accepted answer must show how to create a string or array of bytes from the "data" returned by

var data = await dataPackageView.GetDataAsync(someFormat);
like image 475
Will Olsen Avatar asked Jun 17 '16 00:06

Will Olsen


1 Answers

if you know its a file you can use the following code

var content = Clipboard.GetContent();

IReadOnlyList<IStorageItem> files = await content.GetStorageItemsAsync();
var file = files.First() as StorageFile;    

From MSDN article on StandardDataFormats

The DataPackage class supports a number of legacy formats for interoperability between Windows Store apps and desktop apps. To retrieve these formats, you pass one of the following strings to the DataPackageView.GetDataAsync method instead of a value from the StandardDataFormats class.

eg

var content = Clipboard.GetContent();
var data = await content.GetDataAsync("PenData"); //Stream for HGLOBAL corresponding to CF_PENDATA        
like image 58
SWilko Avatar answered Sep 25 '22 22:09

SWilko