使用PictureBox进行C#碰撞检测

时间:2016-03-03 11:35:31

标签: c# picturebox collision

我有一个程序可以在表单中添加一个图片框,但我想确保图片框不与任何现有的图片框重叠。

目前我有

PictureBox PB = new PictureBox();
PB.Name = "Table " + number;
PB.BackgroundImage = Image.FromFile("C:\\table.png");
PB.Size = new Size(65,65);

//x = x + 70;
//y = y + 50;
PB.Location = new Point(LocX, LocY);
PB.MouseDoubleClick += new MouseEventHandler(this.PB_DoubleClick);
foreach (Control picturebox in this.Controls)
{
    if (PB.Bounds.IntersectsWith(picturebox.Bounds))
    {
        //Collision
    }
    else
    {
        this.Controls.Add(PB);

    }
}

然而,控件仍然可以重叠在一起,请参阅:

Overlap example

显然,我在代码中没有做的事情,但我看不到什么?

1 个答案:

答案 0 :(得分:2)

你的foreach是错误的,因为每当一个图片框没有相交时你添加新的盒子,但另一个可能会这样做,尝试这样的事情:

var
  fmMain: TfmMain;
  MyMsg: Cardinal;

implementation

uses
  uSettings;

{$R *.dfm}

procedure TfmMain.AppMessage(var Msg: TMsg; var Handled: Boolean);
begin
  if (Msg.Message = MyMsg) then
  begin
    beep;

    Application.Restore;
    Application.MainForm.Visible := True;
    SetForeGroundWindow(Application.MainForm.Handle);
    Handled := True;
  end;
end;

procedure TfmMain.FormCreate(Sender: TObject);
begin
  Application.OnMessage := AppMessage;
end;