同时移动2个表单

时间:2011-11-18 16:27:16

标签: c# winforms winapi

我在这里停留了一下。我试图在不使用OnMove,LocationChanged,Docking等的情况下同时移动2个表单。

与其位置进行交互的唯一方法是覆盖WndProc。可能有用的东西是表单A是表单B的所有者。因此,每当A移动时,我也想移动B.不是同一个地方,而是相同的距离。

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x0084)
        {
              Form[] temp = this.OwnedForms;

              if(temp.Length > 0) 
              {
                    /* moving temp[0] to the same ratio as this form */
              }

              m.Result = (IntPtr)2;
              return;
        }
        base.WndProc(ref m);
    }

A和B都具有相同的WndProc,因为它们是来自同一类的2个对象。

2 个答案:

答案 0 :(得分:3)

避免使用LocationChanged事件没有任何意义:

    private Point lastPos;

    protected override void OnLoad(EventArgs e) {
        base.OnLoad(e);
        lastPos = this.Location;
    }

    protected override void OnLocationChanged(EventArgs e) {
        base.OnLocationChanged(e);
        foreach (var frm in this.OwnedForms) {
            frm.Location = new Point(frm.Location.X + this.Left - lastPos.X,
                frm.Location.Y + this.Top - lastPos.Y);
        }
        lastPos = this.Location;
    }

    protected override void WndProc(ref Message m) {
        // Move borderless window with click-and-drag on client window
        if (m.Msg == 0x84) m.Result = (IntPtr)2;
        else base.WndProc(ref m);
    }

答案 1 :(得分:-1)

我设法解决了这个问题:

protected override void WndProc(ref Message m)
{
    Form temp = this.Owner;

    if (m.Msg == 0x0084)
    {
          m.Result = (IntPtr)2;
          return;
    }

    if (m.Msg == 0x0216 && temp != null)
    {
         if (!movedonce)
         {
              oldlocationx = this.Location.X;
              oldlocationy = this.Location.Y;
              movedonce = true;
         }

         temp.Location = new Point(temp.Location.X + this.Location.X - oldlocationx, temp.Location.Y + this.Location.Y - oldlocationy);
         oldlocationx = this.Location.X;
         oldlocationy = this.Location.Y;
    }

    base.WndProc(ref m);
}