同时移动两种形式

本文关键字:两种 移动 | 更新日期: 2023-09-27 18:15:02

我被卡在这里了。我试图同时移动2个窗体,而不使用OnMove, LocationChanged, Docking等。

与它们的位置交互的唯一方法是重写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,因为它们是来自同一个类的两个对象。

同时移动两种形式

避免使用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);
    }

我设法解决了这个问题:

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);
}