C# 切换按钮的颜色
我创建了一个包含线程的程序。有一个带面板的按钮,当通过线程访问面板时,按钮应自动将其背景颜色变为粉红色。再次按下按钮时,它应变为绿色。我的问题是,当线程访问该面板时,按钮不会变成粉红色,而是保持默认颜色。但当我点击时,它会改变颜色 以下是我所做的:- //这是按钮单击事件C# 切换按钮的颜色,c#,multithreading,button,togglebutton,C#,Multithreading,Button,Togglebutton,我创建了一个包含线程的程序。有一个带面板的按钮,当通过线程访问面板时,按钮应自动将其背景颜色变为粉红色。再次按下按钮时,它应变为绿色。我的问题是,当线程访问该面板时,按钮不会变成粉红色,而是保持默认颜色。但当我点击时,它会改变颜色 以下是我所做的:- //这是按钮单击事件 public void btn_Click(object sender, System.EventArgs e) { locked = !locked; //makes the locked varia
public void btn_Click(object sender, System.EventArgs e)
{
locked = !locked; //makes the locked variable true if it is false and vice versa
this.btn.BackColor = locked ? Color.Pink : Color.Green;
lock (this)
{
if (!locked)
{
Monitor.Pulse(this);
}
}
}
这是执行时的代码,按钮应自动变为粉红色
public void start2()
{
Thread.Sleep(delay);
while (true)
{
semaphore.Signal();
this.ZeroPlane();
panel.Invalidate();
buff.read(ref colour, ref status);
for (int k = 0; k < 5; k++)
{
panel.Invalidate();
this.movePlane(xDelta, yDelta);
Thread.Sleep(delay);
locked = true;
}
if (status == "1" || status =="2" || status == "3") //checks whether it has arrived at the destination
{
lock (this)
{
while (locked)
{
Monitor.Wait(this); //keep the plane in the hub until the button is pressed.
}
}
semaphore.Wait();
buff.write(this.colour, this.status); //overwrites the buffer
buff.read(ref colour, ref status);
for (int p = 0; p < 5; p++)
{
this.westEast = true;
this.movePlane(0, 20);
Thread.Sleep(delay);
panel.Invalidate();
}
nextSemaphore.Wait();
nextBuffer.write(this.colour, "0");
this.colour = Color.Yellow;
this.status = null;
}
}
public void start2()
{
睡眠(延迟);
while(true)
{
semaphore.Signal();
这个.ZeroPlane();
panel.Invalidate();
浅黄色读取(参考颜色、参考状态);
对于(int k=0;k<5;k++)
{
panel.Invalidate();
此.movePlane(xDelta,yDelta);
睡眠(延迟);
锁定=真;
}
if(status==“1”| | status==“2”| | status==“3”)//检查它是否已到达目的地
{
锁(这个)
{
while(锁定)
{
监视器。等等(这个);//把飞机停在中心直到按钮按下。
}
}
semaphore.Wait();
buff.write(this.color,this.status);//覆盖缓冲区
浅黄色读取(参考颜色、参考状态);
对于(int p=0;p<5;p++)
{
this.westEast=正确;
这个。移动平面(0,20);
睡眠(延迟);
panel.Invalidate();
}
nextSemaphore.Wait();
下一个缓冲区。写下(this.color,“0”);
this.Color=Color.Yellow;
this.status=null;
}
}
按下按钮时,按钮会查看已锁定的变量,如果按钮已锁定(将为粉红色),则立即将其设置为未锁定(绿色)when意味着当您更改颜色时,它只能变为绿色,您没有给它变为粉红色的机会。Start2
方法设置locked
变量,但是您无法通过额外测试来更改按钮(我假设您已经发现,从另一个线程更改表单是不可能的)
您有两个选项,一个是每100毫秒触发一次的计时器,一个是测试“锁定”变量并将按钮设置为粉红色的计时器。该计时器将位于窗体线程上,因此允许更改按钮属性
否则,您可以创建一个充当变量侦听器的事件,并从线程内部调用要触发的事件。我找到了解决方案。我只是使用了按钮的变量名更改了按钮的背景颜色
以下是我所做的:
//more code here
if (status == "1" || status =="2" || status == "3") //checks whether it has arrived at the destination
{
this.btn.BackColor = Color.Pink; //just change its colour to pink.
lock (this)
{
//rest of the code
也许我遗漏了什么,但我看不出按钮的颜色受线程的影响。@Shehan.W你真的需要线程吗?是的,我需要线程。