【问题标题】:locking winform location锁定winform位置
【发布时间】:2012-12-28 23:43:58
【问题描述】:

我有一个主窗体窗口,它将弹出一个新的窗体窗口。我想锁定弹出窗体的位置,使窗口不能移动,它会与主窗体同时移动。 (所以如果用户拖动主窗体,弹出窗口也会随之移动)

在网站上进行了搜索,有些是这样的:

this.FormBorderStyle=System.Windows.Forms.FormBorderStyle.None

我将 Locked 属性设置为 True,但这不起作用。

但我想保留边界。锁定表单的正确方法是什么?

【问题讨论】:

  • 这违反了许多 UI 可用性规则。当用户最小化/最大化主窗口时,内爆非常糟糕。简单直观的方法是让你的主窗口更大。将用户控件停靠或锚定到右侧。
  • 是的,这就是我想做的。这就像一个小日志,应该在主窗口的一侧弹出什么。最好的方法是什么?

标签: c# winforms controls


【解决方案1】:
public class Form1
{
    private Form2 Form2 = new Form2();
    private Point form2Location;
    private Point form1Location;
    private void Button1_Click(System.Object sender, System.EventArgs e)
    {
        form1Location = this.Location;
        Form2.Show();
        form2Location = Form2.Location;
    }

    private void Form1_Move(System.Object sender, System.EventArgs e)
    {
        Form2.IsMoving = true;
        Point form2OffSetLocation = new Point(this.Location.X - form2Location.X, this.Location.Y - form2Location.Y);
        Form2.Location = form2OffSetLocation;
        Form2.IsMoving = false;
    }
}    

public class Form2
{

    public bool IsMoving;
    private void Form2_Move(System.Object sender, System.EventArgs e)
    {
        if (IsMoving) return; 
        if (staticLocation.X != 0 & staticLocation.Y != 0) this.Location = staticLocation; 
    }

    private Point staticLocation;
    private void Form2_Load(System.Object sender, System.EventArgs e)
    {
        staticLocation = this.Location;
    }
}

我同意 Hans 的观点,我想一旦你看到它看起来有多狡猾,你可能也会同意。

【讨论】:

    【解决方案2】:

    你可以这样做(取自here):

    protected override void WndProc(ref Message message)
    {
        const int WM_SYSCOMMAND = 0x0112;
        const int SC_MOVE = 0xF010;
    
        switch(message.Msg)
        {
            case WM_SYSCOMMAND:
               int command = message.WParam.ToInt32() & 0xfff0;
               if (command == SC_MOVE)
                  return;
               break;
        }
    
        base.WndProc(ref message);
    }
    

    【讨论】:

    • 这个位会导致错误:0×0112; 它说 ; expected 这是 c# 的正确语法吗?
    • @sd_dracula 出于某种原因,当我复制和粘贴 x 时,它是一个乘号 (×)。如果你用 x 替换它,它应该可以编译,就像上面的编辑一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    相关资源
    最近更新 更多