这是我的代码:
public partial class Form1 : Form
{
Graphics g;
bool mouseUP = false;
double dimensions = 4.0;
SolidBrush brush;
public Form1()
{
InitializeComponent();
g = this.CreateGraphics();
brush = new SolidBrush(Color.Black);
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
mouseUP = false;
backgroundWorker1.RunWorkerAsync(e);
}
private bool mouseIsUP()
{
return mouseUP;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
mouseUP = true;
MessageBox.Show("UP");
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(0,e.Argument);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
while (!mouseIsUP())
{
g.FillEllipse(brush, ((MouseEventArgs)e.UserState).X - (int)dimensions / 2, ((MouseEventArgs)e.UserState).Y - (int)dimensions / 2, (int)dimensions, (int)dimensions);
dimensions += 0.2;
Thread.Sleep(10);
}
}
}
为什么事件mouseUP永远不会发生? 如果我删除了,我可以看到MessageBox“UP”...
我正在尝试在按下鼠标时制作更大的椭圆。当我释放鼠标按钮时,椭圆不应该长得更多。
提前致谢!
答案 0 :(得分:1)
因为您没有将事件处理程序绑定到事件(假设您没有错过该代码)。
例如,在Form1的构造函数中,您可以添加
MouseUp += Form1_MouseUp;
MouseDown += Form1_MouseDown;
答案 1 :(得分:1)
看起来后台工作者以某种方式阻止了代码中的事件循环。 DoWork在哪里召唤工人?
我认为更好的解决办法可能是覆盖OnPaint方法,检查鼠标是否在那里,然后绘制圆圈。
bool isMouseDown = false;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
isMouseDown = true;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
isMouseDown = false;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (isMouseDown)
{
g.FillEllipse(brush, ((MouseEventArgs)e.UserState).X - (int)dimensions / 2, ((MouseEventArgs)e.UserState).Y - (int)dimensions / 2, (int)dimensions, (int)dimensions);
dimensions += 0.2;
Thread.Sleep(10);
}
}