C# 计时器超时时清除剪贴板
我用一个计时器来做记录C# 计时器超时时清除剪贴板,c#,windows-phone-7,C#,Windows Phone 7,我用一个计时器来做记录 System.Threading.Timer clipboardTimer = new Timer(ClearClipboard); 接下来,我将其间隔更改为 clipboardTimer.Change(1000, 30000); 在handle timeout函数中,即ClearClipboard,我想按如下方式清除剪贴板: void ClearClipboard(object o) { Clipboard.SetText(""); } 但是有系统。未经授
System.Threading.Timer clipboardTimer = new Timer(ClearClipboard);
接下来,我将其间隔更改为
clipboardTimer.Change(1000, 30000);
在handle timeout函数中,即ClearClipboard
,我想按如下方式清除剪贴板:
void ClearClipboard(object o)
{
Clipboard.SetText("");
}
但是有
系统。未经授权的例外。也许,这是因为有两个不同的线程。那么,如何有效地调用clear clipboard?要求调度程序运行clipboard.SetText(“”),因为计时器的超时事件在非UI线程上引发,并且您无法从另一个线程更改UI线程创建的控件
试试这样的
void ClearClipboard(object o)
{
Dispatcher.Invoke( () => { Clipboard.SetText(""); });
}
您需要在GUI线程上调用方法。您可以通过调用Control.Invoke
:
control.Invoke(new Action(() => control.Text = "new text")));
发生此错误的原因是计时器
事件在UI线程以外的单独线程上触发。您可以通过以下两种方式之一更改UI元素。第一个是告诉对象在UI线程上执行代码。如果带有计时器的对象是依赖对象
(例如PhoneApplicationPage
),则可以使用该属性。这是通过该方法完成的
如果对象不是依赖对象
,则可以使用该对象访问调度程序
void ClearClipboard(object o)
{
Deployment.Current.Dispatcher.BeginInvoke(() => Clipboard.SetText(""));
}
第二个选项是使用而不是计时器。dispatchermer
事件在UI线程上启动
// 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("");
}
谢谢@Shawn Kendrot我使用了Dispatchermer,它运行良好。
// 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("");
}