C#線程間不能調(diào)用剪切板的解決方法
最近做一個(gè)C#項(xiàng)目,需要用到線程,而且要用到剪切板,創(chuàng)建了一個(gè)子線程之后發(fā)現(xiàn)在子線程中剪切板上獲取不到數(shù)據(jù),經(jīng)過一番查找與測試最終該問題得以解決,現(xiàn)將解決方法歸納如下,供大家參考:
第一步:
public void btnAutoFocus_Click(object sender,EventArgs e) { Thread myThread = new Thread(msc.AutoFocusArithmetic); //注意,一般啟動(dòng)一個(gè)線程的時(shí)候沒有這句話,但是要操作剪切板的話這句話是必需要加上的, //因?yàn)榧羟邪逯荒茉趩尉€程單元中訪問 //這里的STA就是指單線程單元 myThread .SetApartmentState(ApartmentState.STA); myThread .Start(); }
第二步:還需要將Program啟動(dòng)類中
static class Program { /// /// 應(yīng)用程序的主入口點(diǎn)。 /// [STAThread] //這句話保留,如果要在主線程中訪問剪切板,這句式必須要的 //如果要在子線程中訪問剪切板,這個(gè)應(yīng)該可以不要,但是默認(rèn)是有的 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()); } }
第三步:這個(gè)是讀取剪切板數(shù)據(jù)
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; }
至此問題得以解決。
相關(guān)文章
npoi2.0將datatable對象轉(zhuǎn)換為excel2007示例
這篇文章主要介紹了npoi2.0將datatable對象轉(zhuǎn)換為excel2007示例的相關(guān)資料2014-04-04Winform自定義控件在界面拖動(dòng)、滾動(dòng)鼠標(biāo)時(shí)閃爍的解決方法
這篇文章介紹了Winform自定義控件在界面拖動(dòng)、滾動(dòng)鼠標(biāo)時(shí)閃爍的解決方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12C# Access數(shù)據(jù)庫增刪查改的簡單方法
這篇文章主要介紹了C# Access數(shù)據(jù)庫增刪查改的簡單方法,有需要的朋友可以參考一下2014-01-01