自己编的小程序“非爱不可”,有个奇怪的小问题
”非爱不可“就是有2个按钮,1个按钮是“爱”,1个是“不爱”,让别人选,一旦鼠标移到“不爱”处,按钮会离开鼠标,让对方无法点到
我拉了2个按钮,爱用btnlove,不爱用btnnlove
下面是我写的鼠标移动到“不爱”按钮时的代码,可以运行,运行开始的时候很好,试验的次数多了后,会有偶尔”不爱“按钮一部分或者全部跑到窗口边界下面的现象,可我明明让“不爱”按钮的TOP在窗口高度减按钮高度之间随机,不应该出现越界的现象,为什么还会出下界?而且我为了不让它出下界,还加了一句IF来验证,可运行程序了仍然会出下界。好奇怪哦,哪位大哥能帮帮我,谢谢
private void btnnlove_MouseMove(object sender, MouseEventArgs e)
{
Random r = new Random();
btnnlove.Top = r.Next(this.Height - btnnlove.Height);
btnnlove.Left= r.Next(this.Width - btnnlove.Width);
//验证按钮“不爱”是否覆盖按钮“爱”,如果覆盖,重新随机
bool check = btnnlove.Location.X >= (btnlove.Location.X - btnlove.Width) && btnnlove.Location.X <= (btnlove.Location.X + btnlove.Width) && btnnlove.Location.Y >= (btnlove.Location.Y - btnlove.Height) && btnnlove.Location.Y <= (btnlove.Location.Y + btnlove.Height);
//出问题后加的这句,想避免出下界的问题
if (btnnlove.Location.Y >= (this.Height - btnnlove.Height)) check = true;
while(check)
{
btnnlove.Top = r.Next(this.Height - btnnlove.Height);
btnnlove.Left = r.Next(this.Width - btnnlove.Width);
check = btnnlove.Location.X >= (btnlove.Location.X - btnlove.Width) && btnnlove.Location.X <= (btnlove.Location.X + btnlove.Width) && btnnlove.Location.Y >= (btnlove.Location.Y - btnlove.Height) && btnnlove.Location.Y <= (btnlove.Location.Y + btnlove.Height);
//出问题后加的这句,想避免出下界的问题
if (btnnlove.Location.Y >= (this.Height - btnnlove.Height)) check = true;
}
}
------解决方案--------------------好象btnnlove.Top = r.Next(this.Height - btnnlove.Height);
中的this.Height的大小包括标题栏
------解决方案--------------------楼上正解,把this.Height改成this.ClientSize.Height就可以了