הדבקה ל - Clipboard מתוך Timer - תיקון 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.
נניח שאתם כותבים קוד כזה.
System.Threading.Timer timer =
new System.Threading.Timer(callbacb, null, 1000, 5000);
private void callbacb(object state)
{
Clipboard.SetData("text", "abcd");
}
הפרמטר הראשון זה המתודה להפעלה, השני זה פרמטר לפונקצייה, השלישי כמה זמן לחכות לפני הפעימה הראשונה, והאחרון הינו ה - interval.
בכל מקרה הקוד יעיף שגיאה:
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.
מכיוון שה - Timer רץ ב - Context שלא מוגדר כ - STA.
במידה ואתם עובדים ב - WinForm application. אפשר פשוט לעבוד עם Timer של System.Windows.Forms או ב - Timer של System.Timers ולתת למאפיין SynchronizingObject את המופע של ה - Form.
אבל במידה ואתם עובדים ב - Context אחר - כמו Windows Service או AddIn בעזרת VSTO, תוכלו להשתמש ב - Timer של System.Threading או ב - Timer של System.Timers, אבל לא תוכלו להגדיר את ה - SynchronizingObject.
הפיתרון שמצאתי, זה לכתוב בצורה עקיפה.
private void callbacb(object state)
{
Thread t = new Thread(new ThreadStart(() =>
{
Clipboard.SetData("text", "abcd");
}));
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
מה שעשינו - זה להפעיל את ה - Timer בכל פעם, אבל במקום לגשת ל - Clipboard מתוך ה - Timer מה שיגרום לשגיאה מכיון שהוא רץ במוד של MTA, אני מייצר Thread חדש ולפני שהוא רץ אני משנה אותו ל - STA ובתוך ה - Thread אני ניגש ל - Clipboard.