How do I update my label1 text in the code below ? I am getting a "The calling thread cannot access this object because a different thread owns it" error. I have read that others have used Dispatcher.BeginInvoke but I do not know how to implement it in my code.
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;
}
}
}
You can try something like this:
if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
string s = IdleTime.ToString();
Dispatcher.BeginInvoke(new Action(() =>
{
label1.Content = s;
}));
}
Read more about Dispatcher.BeginInvoke Method here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With