有谁能看出问题出在哪里?
UserActivityHook actHook;
private void Form1_Load(object sender, EventArgs e)
{
actHook = new UserActivityHook();
actHook.KeyPress += new KeyPressEventHandler(klawisze);
actHook.KeyDown += new KeyEventHandler(klawisze2);
actHook.Start();
}
public void pw()
{
while (!stopIt)
{
SetCursorPos(576, 363);
Thread.Sleep(50);
SetCursorPos(650, 363);
Thread.Sleep(50);
SetCursorPos(650, 430);
Thread.Sleep(50);
}
}
public void Stop()
{
stopIt = true;
}
private volatile bool stopIt;
public void dw()
{
while (!stopIt)
{
SetCursorPos(860, 350);
Thread.Sleep(50);
SetCursorPos(890, 350);
Thread.Sleep(50);
SetCursorPos(890, 380);
Thread.Sleep(50);
}
}
public void klawisze(object sender, KeyPressEventArgs e)
{
Thread w1 = new Thread(new ThreadStart(pw));
Thread w2 = new Thread(new ThreadStart(dw));
try
{
if (e.KeyChar == 21) //CTRL + SHIFT + U
{ //1
stopIt = false;
w1.Start();
if (e.KeyChar == 9)
{
Stop();
w1.Join();
}
}
if (e.KeyChar == 9) //CTRL + SHIFT + I
{ //2
stopIt = false;
w2.Start();
if (e.KeyChar == 21)
{
Stop();
w2.Join();
}
}
}
当我按下第一个热键并绘制第二个三角形(+停止绘制第一个)时按下第二个热键,但是它同时绘制2个三角形时应该绘制延迟的三角形...我迷惑了...
答案 0 :(得分:0)
您If
查询无法调用Stop()
或Join
线程的原因。相反,它将启动一个新的线程。你的线程也是本地的,你总是创建新的,所以你不能全局阻止它们
if (e.KeyChar == 21)
{
stopIt = false;
w1.Start();
if (e.KeyChar == 9) // How should this work? e.Keychar is 21 if the first query passed
{
// This will never be executed
Stop();
w1.Join();
}
}
编辑:因为你问
private static Thread w1;
private static Thread w2;
public void klawisze(object sender, KeyPressEventArgs e)
{
try
{
if (e.KeyChar == 21) //CTRL + SHIFT + U
{
if (w2 != null)
{
Stop();
w2.Join();
while (w2.IsAlive)
{
Thread.Sleep(100);
}
}
stopIt = false;
w1 = new Thread(new ThreadStart(pw));
w1.Start();
}
if (e.KeyChar == 9) //CTRL + SHIFT + I
{ //2
if (w1 != null)
{
Stop();
w1.Join();
while (w1.IsAlive)
{
Thread.Sleep(100);
}
stopIt = false;
}
w2 = new Thread(new ThreadStart(dw));
w2.Start();
}
}