C # the problem that the clipboard cannot be called between threads
Recently, a project used threads and clipboard. After creating a subthread, I found that no data was obtained on the clipboard in the subthread. At that time, I was particularly puzzled, finally, the solution is summarized as follows:
Step 1:
Public void btnAutoFocus_Click (object sender, EventArgs e)
{
Thread myThread = new Thread (msc. AutoFocusArithmetic );
// Note that this statement is not used when a thread is started. However, to operate the clipboard, this statement must be added, because the clipboard can only be in a single line.
// Process Unit access. The STA here refers to a single thread unit.
MyThread. SetApartmentState (ApartmentState. STA );
MyThread. Start ();
}
Step 2: you also need to set the Program startup class
Static class Program
{
///
/// Main entry point of the application.
///
[STAThread] // This sentence is retained. If you want to access the clipboard in the main thread, this sentence is required. If you want to access the clipboard in the Child thread, this sentence should be optional, but there are some by default, but I have never tested this. What is the result of this sentence? I will post a blog post after I have time to test it.
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: 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;
}