2013-07-20 44 views
11

我曾嘗試這樣的代碼:錯誤而試圖複製字符串到剪貼板

Clipboard.SetText("Test!"); 

而且我得到這個錯誤:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.

我怎樣才能解決這個問題?

+0

你是否試圖從後臺線程調用這個方法('Clipboard.SetText()')?你能給我們更多的上下文(即圍繞該函數調用的代碼)嗎? –

回答

10

[STAThread]以上的主要方法:

[STAThread] 
static void Main() 
{ 
} 
+0

我猜他正在使用WinForms,所以他無法訪問'Main'。 –

+0

@newStackExchangeInstance我自己在WinForms中做了這些剪貼板應用程序之一,所以我很確定這會爲他工作:) – Thousand

+0

不說它不會工作,只是說在WinForms上編輯'Main'是一個PITA。 –

26

你需要專門調用該方法,因爲它使用了一些遺留代碼。試試這個:

Thread thread = new Thread(() => Clipboard.SetText("Test!")); 
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA 
thread.Start(); 
thread.Join(); //Wait for the thread to end 
+1

*什麼*使用遺留代碼?剪貼板? COM不是「傳統」。 –

+0

這對於在Selenium測試中檢查剪貼板內容非常有用,例如如果你有一個複製到剪貼板按鈕。 –

+1

這解決了我的錯誤。添加屬性沒有。 – syonip