1

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

  • Clear the Clipboard
  • Call myGrid.Copy()

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!

cacau
  • 3,606
  • 3
  • 21
  • 42
  • just to eliminate the obvious; you've dealt with empty fields? ie. fields that are `null` that should hold data? – Ben Apr 14 '14 at 05:56
  • Yep - having the same data in the table works 1 out of 3 times in one specific example. So it must be something outside of our app - I suppose.. – cacau Apr 14 '14 at 05:57

1 Answers1

3

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

Community
  • 1
  • 1
cremor
  • 6,669
  • 1
  • 29
  • 72
  • Hmm - Interesting. Is there a way to tell which process currently owns the clipboard so we can tell the user, i.e. if even the retry-scheme does eventually fail? – cacau Apr 14 '14 at 07:13
  • @cacau I've edited the answer to show how to get the process name. – cremor Apr 14 '14 at 07:17
  • Added that plus the retry approach and it appears to work on our local test plus at least one customer system - cheers! – cacau Apr 14 '14 at 12:22