0

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.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Manoj kumar
  • 134
  • 2
  • 3
  • 10
  • 4
    _It is not working_ is not a good explanation about problem. What is your full code? Do you get any exception or error message? Be more specific.. – Soner Gönül Jul 25 '13 at 07:05
  • 2
    MSDN: "The Clipboard class can only be used in threads set to single thread apartment (STA) mode." – Adrian Fâciu Jul 25 '13 at 07:10

2 Answers2

3

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?

Community
  • 1
  • 1
CamW
  • 3,223
  • 24
  • 34
0

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();