Manoj kumar
Manoj kumar

Reputation: 134

Clipboard.getImage not working inside a thread

I was trying to read images from the clipboard and save it in a specified folder using Clipboard.getImage()

The function works fine if it standalone. When I was using the function inside a thread its not working.

Upvotes: 0

Views: 2031

Answers (2)

Trianon
Trianon

Reputation: 1

When you trying to read images from the clipboard inside a thread you must set thread ApartmentState to STA. Try this:

Thread t = new Thread(DoSomething());
t.SetApartmentState(ApartmentState.STA);
t.Start();

Upvotes: 0

CamW
CamW

Reputation: 3363

This is a STA vs MTA thread issue. You won't have access to the clipboard from a MTA thread. for reference:

This works:

    [STAThread()]
    static void Main(string[] args)
    {
        Image img = Clipboard.GetImage();
        img.Save(@"c:\temp\myimg.png",System.Drawing.Imaging.ImageFormat.Png);
    }

This doesn't - null reference:

    [MTAThread()]
    static void Main(string[] args)
    {
        Image img = Clipboard.GetImage();
        img.Save(@"c:\temp\myimg.png",System.Drawing.Imaging.ImageFormat.Png);
    }

Have a look at this thread for STA background thread related solutions: How can I make a background worker thread set to Single Thread Apartment?

Upvotes: 4

Related Questions