C threads cannot call the clipboard solution

  • 2020-06-19 11:39:05
  • OfStack

Recently, I was working on an C# project, which required a thread and a clipboard. After creating a child thread, I found that no data could be obtained from the clipboard. After repeated searching and testing, the problem was finally solved.

Step 1:


public void btnAutoFocus_Click(object sender,EventArgs e)
{
Thread myThread = new Thread(msc.AutoFocusArithmetic);
// Pay attention to, 1 A startup 1 You don't have that sentence in 10 threads, but you do have to add it in order to manipulate the clipboard, 
// Because the clipboard can only be accessed from a single threaded unit 
// Here, STA It's a single thread unit 
myThread .SetApartmentState(ApartmentState.STA); 
myThread .Start();
}

Step 2: You also need to put the Program startup class in


static class Program
{
///
///  The main entry point to the application. 
///

[STAThread] // If you want to access the clipboard in the main thread, this is a must 
// If you want to access the clipboard in a child thread, this should not be done, but the default is yes 
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
//Application.Run(new TestRGBPixelThumbForm());
//Application.Run(new TestImageForm());
//Application.Run(new TestJudgeDefinitionForm());
//Application.Run(new TestVirusForm());
}
}

Step 3: This is to read the clipboard data


private Image GetCaptureImage()
{
IDataObject iData = Clipboard.GetDataObject();
Image img = null;
if (iData != null)
{
if (iData.GetDataPresent(DataFormats.Bitmap))
{
img = (Image)iData.GetData(DataFormats.Bitmap);
}
else if (iData.GetDataPresent(DataFormats.Dib))
{
img = (Image)iData.GetData(DataFormats.Dib);
}
}
return img;
}

So far the problem has been solved.


Related articles: