Search code examples
c#windows-phone-7

clear clipboard when timer timeouts


I am using a timer as

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

Next, I change its interval as

clipboardTimer.Change(1000, 30000);

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

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

but there is System.Unauthorised exception. Maybe, this is because there are two different threads. So, how can I invoke clear clipboard efficiently?


Solution

  • This error occurs because the Timer event fires on a separate thread than the UI thread. You can change a UI element in one of two ways. The first is to tell the Dispatcher object to execute the code on the UI thread. If your object with the Timer is a DependencyObject (e.g. PhoneApplicationPage), you can use the Dispatcher property. This is done with 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 the DispatcherTimer instead of the Timer. The DispatcherTimer event does fire on the UI 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("");
    }