Skip to content

Commit

Permalink
Merge pull request #51 from deadlydog/FixCopyToClipboardIssue
Browse files Browse the repository at this point in the history
Fix copy to clipboard issue
  • Loading branch information
deadlydog authored Dec 16, 2020
2 parents 5d15f46 + c1b650a commit 86ac0fd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
6 changes: 6 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## v1.8.5 - December 16, 2020

Fixes:

- Perform retries on copying to clipboard to prevent race condition error.

## v1.8.2 - November 25, 2020

Fixes:
Expand Down
33 changes: 19 additions & 14 deletions src/PathLengthCheckerGUI/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,21 +286,26 @@ private string GetPathsAsCsvString(bool includeLength)
/// <param name="text">A string for the clipboard</param>
private static void SetClipboardText(string text)
{
try
// Copying to the clipboard can be unreliable, so we need to implement retries: https://stackoverflow.com/a/69081/602585
int maxAttempts = 100;
int millisecondsBetweenAttempts = 10;
for (int attempts = 1; attempts <= maxAttempts; attempts++)
{
Thread thread = new Thread(
// Using Clipboard.SetText(string) can result in a race condition that throws an exception, so use SetDataObject instead.
// For more info, see: https://stackoverflow.com/a/39125098/602585
() => Clipboard.SetDataObject(text, true)
);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred while copying text to the clipboard:{Environment.NewLine}{Environment.NewLine}{ex.Message}", "Error Occurred");
Debug.WriteLine(ex.ToString());
try
{
Clipboard.SetText(text);
return;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());

if (attempts == maxAttempts)
{
MessageBox.Show($"An error occurred while copying text to the clipboard:{Environment.NewLine}{Environment.NewLine}{ex.Message}", "Error Occurred Copying To Clipboard");
}
}
System.Threading.Thread.Sleep(millisecondsBetweenAttempts);
}
}

Expand Down

0 comments on commit 86ac0fd

Please sign in to comment.