cacau
cacau

Reputation: 3646

Intermittent exceptions when copying from WPF DataGrid (CLIPBRD_E_CANT_OPEN)

My app uses the Copy() method of DataGrid to retrieve all data for exporting to CSV and other formats. All I do is

Now that usually works fine - except for <1% of my users they receive an exception.

Even on these particular systems it happens only occasionally, i.e. copying works the first time but then fails on following attempts (that is, with identical, valid table contents copying works 1 out of 3 times!) with a CLIPBRD_E_CANT_OPEN error and stack traces like

   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Windows.Clipboard.Flush()
   at System.Windows.Controls.DataGrid.OnExecutedCopy(ExecutedRoutedEventArgs args)

The .net Version is usually 4.0.30319.x (but again the problem doesn't appear to be related to a particular framework version as far as I can tell).

As the export is a crucial feature of the app this problem has a pretty huge impact..
Any ideas how to work around this problem would be much appreciated!

Upvotes: 1

Views: 1828

Answers (1)

cremor
cremor

Reputation: 6876

The clipboard is a shared resource in Windows. If any other program on the PC currently uses the clipboard, you'll get exceptions like that one. Any clipboard operations you do must be coded extremley careful. Handle exceptions. Retry a few times, maybe after some wait time. If it still doesn't work after some retries, notify the user that he has to try it again later.

There have been applications that were (or maybe are) completly buggy regarding the clipboard. E.g., there was a version of Skype that completely locked the clipboard during the whole runtime of Skype.

There are some native Win32 functions that you can call to get the window and process that is currently blocking the clipboard. Look at GetOpenClipboardWindow, GetWindowText and GetWindowThreadProcessId in User32.dll. Then use Process.GetProcessById(processId).ProcessName to get the process name from the given Id.

You can find some more information in this similar question: OpenClipboard Failed when copy pasting data from wpf DataGrid

Upvotes: 3

Related Questions