This question already has an answer here:
I am setting up a Timer
within a method with an interval of 1000
so that every second it will type another corresponding character into a Textbox
(pretty much automating typing). When I check for _currentTextLength == _text.Length
I get the threading error "The calling thread cannot access this object because a different thread owns it."
public void WriteText(string Text)
{
timer = new Timer();
try
{
_text = Text;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed_WriteText);
timer.Interval = 1000;
timer.Enabled = true;
timer.Start();
}
catch
{
MessageBox.Show("WriteText timer could not be started.");
}
}
// Write Text Timer Event
void timer_Elapsed_WriteText(object sender, ElapsedEventArgs e)
{
TextBoxAutomationPeer peer = new TextBoxAutomationPeer(_textBox);
IValueProvider valueProvider = peer.GetPattern(PatternInterface.Value) as IValueProvider;
valueProvider.SetValue(_text.Substring(0, _currentTextLength));
if (_currentTextLength == _text.Length) // Error here
{
timer.Stop();
timer = null;
return;
}
_currentTextLength++;
}
The variable _text
is a private class variable and so is _currentTextLength
. _textBox
is self explanatory.
Any way to solve this?
this simply means that you are trying to access some UI element from a thread other then it was created on. To overcome this you need to access it like this
Note: If you want to check whether you can access it normally or not you can use this
Use a DispatcherTimer instead of a Timer.
Should solve your problem.