Click here to Skip to main content
15,894,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying place a 32bit binary value into the clipboard. The user hits a button ("Copy Binary") and I want that button to place the ANSI binary encoded value of the 32 bit value in my code into the clipboard. Here is the code I am trying:

C#
//byte[] bytes contains my 32 bit value as a 4 byte array.

            Clipboard.SetData(System.Windows.DataFormats.Text, Encoding.Default.GetString(bytes));


This works correctly if the values in "bytes" doesn't contain a "00", i.e. 0x12345678.

However, if the value is 0x12005678 it will stop after encoding just 0x12 and I will only have one byte in my clipboard.

How can I make sure that the entire byte array is encoded?
Posted
Updated 20-Aug-12 5:03am
v3

CF_TEXT is a standard gateway between every windows desktop apps to copy paste strings. Putting binary data as CF_TEXT to the clipboard is nonsense. Anyway, the clipboard handles this type specially so its a luck that you havent crashed. If you put some data to the clipboard that isn't standard and is recognized only by your program or a set of your programs then you should register a new clipboard format and copy/paste your data with that format: Here is an article how to do that in C#: Saving and obtaining custom objects to/from Windows Clipboard[^]

Another solution to your problem can be converting your binary value to the string representation of the number like "365" and storing that as CF_TEXT on the clipboard, then you have to convert it back when you paste it in your program. This way you can copy paste a number to your program even from a text file with notepad.
 
Share this answer
 
Comments
Adam7869 20-Aug-12 11:02am    
Thanks for the reply. I originally thought the issue was with the Encoding.Default.GetString(bytes) part, but you are right, it occurs when putting it into the clipboard. Thanks!
pasztorpisti 20-Aug-12 12:48pm    
You are welcome! Your problem was that many old-timer programs (and maybe the low-level .net implementation too) uses the clipboard CF_TEXT type as a null terminated string. Thats unhealthy to your integer when some of the bytes in the middle happen to be zeros... :-)
You can't convert a binary value to a string and expect it to work as the encoding for ASCII, or any other for that matter, will interpret the byte data differently, thereby altering it on the receiving end.

This is the case in your example as Windows, internally, uses a null (0x00) to terminate "ASCII" strings. So, the string you put on the clipboard is a single character long, not including the terminator.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900