I am trying to operate threads with key events, I managed to make them start by hitting two keys (i.e. "E" and "R" for two thread), but I can't stop them by realeasing the keys, keyup event doesnt work for some reason. (After starting the action and then stopping it, I would like to restart them instantly... so no timer needed...)
C# Code:
private void Yawspeed_KeyDown(object sender, KeyEventArgs e)
{
Thread yawspeedRightThread = new Thread(new ThreadStart(YawspeedRightThread));
Thread yawspeedLeftThread = new Thread(new ThreadStart(YawspeedLeftThread));
if (e.KeyCode == Keys.E)
{
yawspeedRightThread.Start();
}
if (e.KeyCode == Keys.R)
{
yawspeedLeftThread.Start();
}
}
((Method would be something like that?:
private void Yawspeed_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.E)
{
yawspeedRightThread.Abort();
}
if (e.KeyCode == Keys.R)
{
yawspeedLeftThread.Abort();
}
}
(Ending...)
private void Yawspeed_Load(object sender, EventArgs e)
{
}
#region Thread Functions
/// <summary>
/// This thread will move your cursor
/// </summary>
public static void YawspeedRightThread()
{
while (true)
...(Rest of the code, thread itself, functions...)
First and foremost you cannot restart a thread. If you start a thread, the thread finishes, and then you try to start that same thread object a second time it will throw an exception telling you that's not possible. You should look into using a Thread Pool instead.
Now assuming you're going to ignore the above and try to do this anyway. Two things to check would be that:
Lastly, make sure that the key up actually isn't getting called. The reason I say this is that Thread.Abort() isn't actually guaranteed to end the thread's execution. It simply throws an exception in the thread. This means that if you did something like added a try catch inside of the thread's function that caught an "Exception" object, the try catch will catch the exception that Abort forced into it and allow the thread to continue executing. This fact is one reason why Abort isn't recommended and people are encouraged to use other mechanisms for ending a thread, like tripping a Boolean.