最近做一個項目,需要用到線程,而且要用到剪切板,創建了一個子線程之后發現在子線程中剪切板上獲取不到數據,當時特別納悶,上網查資料,最后終于搞定,現將解決方法歸納如下:
第一步:
public void btnAutoFocus_Click(object sender,EventArgs e)
{
Thread?myThread = new Thread(msc.AutoFocusArithmetic);
//注意,一般啟動一個線程的時候沒有這句話,但是要操作剪切板的話這句話是必需要加上的,因為剪切板只能在單線
//程單元中訪問,這里的STA就是指單線程單元
myThread?.SetApartmentState(ApartmentState.STA); ?
myThread?.Start();
}
第二步:還需要將Program啟動類中
static class Program
? ? {
? ? ? ? /// <summary>
? ? ? ? /// 應用程序的主入口點。
? ? ? ? /// </summary>
? ? ? ? [STAThread] ?//這句話保留,如果要在主線程中訪問剪切板,這句式必須要的,如果要在子線程中訪問剪切板,這個應該可以不要,但是默認是有的,不過這個我沒有測試過不要這句話是什么結果,后面有時間測試之后再發博文
? ? ? ? static void Main()
? ? ? ? {
? ? ? ? ? ? Application.EnableVisualStyles();
? ? ? ? ? ? Application.SetCompatibleTextRenderingDefault(false);
? ? ? ? ? ? Application.Run(new MainForm());
? ? ? ? }
? ? }
第三步:這個是讀取剪切板數據,
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;
}