锁定winform位置

时间:2013-01-14 22:46:51

标签: c# winforms controls

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

在网站上搜索过,有些人这样做了:

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

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

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

2 个答案:

答案 0 :(得分:1)

你可以这样做(取自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);
}

答案 1 :(得分: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;
    }
}

我同意汉斯的观点,我认为一旦你看到它看起来多么狡猾,你也可能同意。