作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如何在下面的代码中更新我的 label1 文本?我收到“调用线程无法访问此对象,因为另一个线程拥有它”错误。我读到过其他人使用过 Dispatcher.BeginInvoke,但我不知道如何在我的代码中实现它。
public partial class MainWindow : Window
{
System.Timers.Timer timer;
[DllImport("user32.dll")]
public static extern Boolean GetLastInputInfo(ref tagLASTINPUTINFO plii);
public struct tagLASTINPUTINFO
{
public uint cbSize;
public Int32 dwTime;
}
public MainWindow()
{
InitializeComponent();
StartTimer();
//webb1.Navigate("http://yahoo.com");
}
private void StartTimer()
{
timer = new System.Timers.Timer();
timer.Interval = 100;
timer.Elapsed += timer_Elapsed;
timer.Start();
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
Int32 IdleTime;
LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
LastInput.dwTime = 0;
if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
string s = IdleTime.ToString();
label1.Content = s;
}
}
}
最佳答案
你可以尝试这样的事情:
if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
string s = IdleTime.ToString();
Dispatcher.BeginInvoke(new Action(() =>
{
label1.Content = s;
}));
}
阅读更多关于 Dispatcher.BeginInvoke Method here 的信息
关于c# - 如何更新 WPF MainWindow 上的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18275119/
我是一名优秀的程序员,十分优秀!