“Current thread must be set to single thread apartment (STA)” error in copy string to clipboard

If you can’t control whether thread runs in STA mode or not (i.e. tests, plugin to some other app or just some code that randomly sends that call to run on no-UI thread and you can’t use Control.Invoke to send it back to main UI thread) than you can run clipboard access on thread specifically configured to be in STA state which is required for clipboard access (which internally uses OLE that actually requires STA).

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)