Clear clipboard on timer timeouts

I use a timer as

System.Threading.Timer clipboardTimer = new Timer(ClearClipboard); 

Then I change my interval to

 clipboardTimer.Change(1000, 30000); 

In the processing timeout function, i.e. ClearClipboard , I want to clear the clipboard as

 void ClearClipboard(object o) { Clipboard.SetText(""); } 

but there is a System.Unauthorised exception. Perhaps this is because there are two different streams. So how can I use transparent clipboard effectively?

+4
source share
3 answers

This error occurs because the Timer event is fired on a separate thread than the UI thread. You can change the user interface element in one of two ways. The first is to tell the Dispatcher object to execute code in the user interface thread. If your Timer object is a DependencyObject (e.g. PhoneApplicationPage ), you can use the Dispatcher property. This is done using the BeginInvoke method.

 void ClearClipboard(object o) { Dispatcher.BeginInvoke(() => Clipboard.SetText("")); } 

If your object is not a DependencyObject , you can use the Deployment object to access the Dispatcher .

 void ClearClipboard(object o) { Deployment.Current.Dispatcher.BeginInvoke(() => Clipboard.SetText("")); } 

The second option is to use DispatcherTimer instead of Timer . The DispatcherTimer event makes fire in the user interface thread!

 // Create the timer DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(3); timer.Tick += TimerOnTick; // The subscription method private void TimerOnTick(object sender, EventArgs eventArgs) { Clipboard.SetText(""); } 
+3
source

Ask Dispatcher to run Clipboard.SetText(""); in the user interface thread because the timeout event of the timeout is raised in a thread other than the UI and you cannot change the controls created by the user interface thread from another thread

Try something like this

 void ClearClipboard(object o) { Dispatcher.Invoke( () => { Clipboard.SetText(""); }); } 
+1
source

You will need the Invoke method in the GUI thread. You can do this by calling Control.Invoke :

  control.Invoke(new Action(() => control.Text = "new text"))); 
+1
source

Source: https://habr.com/ru/post/1485926/


All Articles