Skip to content

Commit

Permalink
Thread safety of image copying
Browse files Browse the repository at this point in the history
  • Loading branch information
emako committed Jan 5, 2025
1 parent 0d1ff89 commit 612fb36
Showing 1 changed file with 3 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ public static void SetClipboardImage(this BitmapSource img)
var thread = new Thread((img) =>
{
if (img == null)
{
return;
}

var image = (BitmapSource)img;

Expand All @@ -36,15 +34,16 @@ public static void SetClipboardImage(this BitmapSource img)
try
{
using var pngMemStream = new MemoryStream();
using var bitmpa = image.ToBitmap();
using var bitmpa = image.Dispatcher?.Invoke(() => image.ToBitmap()) ?? image.ToBitmap();
var data = new DataObject();

bitmpa.Save(pngMemStream, ImageFormat.Png);
data.SetData("PNG", pngMemStream, false);

Clipboard.SetDataObject(data, true);
}
catch { }
catch { } // Clipboard competition leading to failure is common
// There is currently no UI notification of success or failure
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start(img);
Expand Down

0 comments on commit 612fb36

Please sign in to comment.