I am working on a small tool that works in the following way:
- show a series of images
- after each image, show an answer window, where the user inputs the answer by pressing a button on the keyboard
- the answer window is shown only for X seconds, after which it disappears, treating the question unanswered
What i did, was i made a class, that extends UserControl
public partial class AnswerDialog : UserControl
{
...
public void ShowAnswerDialog()
{
ResponseItemType = Settings.ItemType.ObjectType_NONE;
this.Show();
allowAnswer = true;
}
public void HideAnswerDialog()
{
allowAnswer = false;
this.Hide();
}
...
private void buttonAnswerItemType0_Click(object sender, EventArgs e)
{
SetAnswer(Settings.ItemType.ObjectType_0);
}
private void buttonAnswerItemType1_Click(object sender, EventArgs e)
{
SetAnswer(Settings.ItemType.ObjectType_1);
}
public void AnswerDialog_KeyDown(object sender, KeyEventArgs e)
{
if (Settings.KeyCodeAnswer0 == e.KeyCode)
{
SetAnswer(Settings.ItemType.ObjectType_0);
}
else if (Settings.KeyCodeAnswer1 == e.KeyCode)
{
SetAnswer(Settings.ItemType.ObjectType_1);
}
}
...
}
It receives the keyboard events from the parent from.
I have a class, where i control this sequence of showing the images and recording the results. In this class, i have the following function:
void AnswerThreadFunc(Object Param)
{
AnswerDialog answerDialog = (AnswerDialog)Param;
answerDialog.ShowAnswerDialog();
}
I did it this way, so i can timeout this thread in the main thread:
Thread answerThread = new Thread(AnswerThreadFunc); //create thread
answerThread.Start(_testWindow.GetAnswerDialog()); //run thread
answerThread.Join(Settings.DurationResponseMs); //wait for thread with timout
_testWindow.GetAnswerDialog().HideAnswerDialog(); //hide if window remained
Settings.ItemType response = _testWindow.GetAnswerDialog().ResponseItemType;
item.GiveResponse(response);
But this will throw the following exception:
Exception thrown: 'System.InvalidOperationException' in System.Windows.Forms.dll An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll Cross-thread operation not valid: Control 'panelMainControl' accessed from a thread other than the thread it was created on.
Thanks you.