Wednesday, October 24, 2007

Clipboard SetData / GetData troubles with VPC and TS

This one of those posts you can categorize is WTF (see me WPF presentation to know what is it) it is not working. However, you, probably will face with the problem now or after.

Symptoms: You are trying to set and get clipboard data from Virtual PC or remote computer by using Terminal Services and nothing happens. When you are using .NET, you're getting Unhandled exception. If you'll dig deeper, you'll find 0x800401D0 (CLIPBRD_E_CANT_OPEN) exception.

Reason: Passing data through TS or VPC pipes bug

Solution: Just retry a couple of times.

Actually, in unmanaged and COM world, you'll never face this problem, because of the way we are handling OleSetClipboard() and OleGetClipboard() methods (which wrapped by .NET Clipboard.GetData/Clipboard.SetData Set/Get Text etc. methods).  So, something like following functions will solve your problems.

public static IDataObject GetRemoteClipboardDataObject()
        {
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    return Clipboard.GetDataObject();
                }
                catch { }
                System.Threading.Thread.Sleep(100);
            }
        }

public static void SetRemoteClipboardDataObject(object data)
        {
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    Clipboard.SetDataObject(data);
                    return;
                }
                catch { }
                System.Threading.Thread.Sleep(100);
            }
        }

Now, to be honest with myself, take a look into one of Clipboard.SetDataObject method signatures in .NET framework 2.0

//Attempts to place data on the system Clipboard the specified number of times and with the specified delay between attempts, optionally leaving the data on the Clipboard after the application exits. 


public static void SetDataObject (
Object data,
bool copy,
int retryTimes,
int retryDelay
)



Don't it looks familiar? :) Have a nice day and be honest with yourselves.

2 comments:

karamba said...

Thanks! It's useful.

karamba said...
This comment has been removed by the author.