我编写了代码,使用带有Windows窗体应用程序的C#在MouseClick
处理的PictureBox
事件上绘制切换按钮。此处单击事件正在触发,但未执行该操作。谁能告诉我我做错了什么?
public partial class Form1 : Form
{
bool flagarrow = false;
public Form1()
{
InitializeComponent();
pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint);
}
void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Point[] arrPoints = new Point[3];
//Identify rectangle area filled by label.
Rectangle lblBackground = (sender as Control).ClientRectangle;
if (false == flagarrow)
{
//(x0,y0) for Triangle.
arrPoints[0].X = lblBackground.Left + 5;
arrPoints[0].Y = lblBackground.Top + 7;
//(x1,y1) for Triangle.
arrPoints[1].X = lblBackground.Left + 5;
arrPoints[1].Y = lblBackground.Top + 17;
//(x2,y2) for Triangle.
arrPoints[2].X = lblBackground.Left + 14;
arrPoints[2].Y = lblBackground.Top + 12;
}
else
{
//(x0,y0) for Triangle.
arrPoints[0].X = lblBackground.Left + 5;
arrPoints[0].Y = lblBackground.Top + 7;
//(x1,y1) for Triangle.
arrPoints[1].X = lblBackground.Left + 15;
arrPoints[1].Y = lblBackground.Top + 7;
//(x2,y2) for Triangle.
arrPoints[2].X = lblBackground.Left + 10;
arrPoints[2].Y = lblBackground.Top + 16;
}
//Fill the Triangle with Black Color.
e.Graphics.FillPolygon(Brushes.Black, arrPoints);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (flagarrow == false)
{
flagarrow = true;
}
else
{
flagarrow = false;
}
}
}
答案 0 :(得分:4)
Winforms没有理由因为您更改了代码中的私有字段而做了一些特殊操作。您必须告诉它您在Paint事件处理程序中使用的条件已更改,并且需要新的绘制。使您的Click事件处理程序如下所示:
flagarrow = !flagarrow;
pictureBox1.Invalidate();
答案 1 :(得分:2)
确实正在引发PictureBox.Click
事件,我怀疑事件处理程序中的代码完全按预期运行。
问题是,你在事件处理程序方法中所做的只是设置变量的值(flagarrow
)。 您尚未执行任何会导致PictureBox
控件重绘自身的内容。其Paint
事件永远不会被触发,因此其外观保持不变。
修复很简单:调用Invalidate
method。这会强制PictureBox
控件重绘自己。虽然我们正在努力,但你可以稍微清理你的代码。
修改Click
事件处理程序中的代码,如下所示:
private void pictureBox1_Click(object sender, EventArgs e)
{
flagarrow = !flagarrow;
pictureBox1.Invalidate();
}
答案 2 :(得分:2)
首先确保您正在挂钩Click事件。我看到这是一个部分类,所以它可能在设计师代码背后。第二次尝试使图片框点击后点击它以强制刷新。
private void pictureBox1_Click(object sender, EventArgs e)
{
if (flagarrow == false)
{
flagarrow = true;
}
else
{
flagarrow = false;
}
pictureBox1.Invalidate();
}
答案 3 :(得分:0)
您只需修改图片框点击事件,如下所示:
private void pictureBox1_Click(object sender, EventArgs e)
{
if (flagarrow == false)
{
flagarrow = true;
}
else
{
flagarrow = false;
}
//Add this following line to repaint the picture box.
pictureBox1.Refresh();
}