新表单显示为C#中主窗体的侧边栏

时间:2016-08-21 13:31:40

标签: c# winforms

enter image description here

当我点击按钮时,我想要显示第二个Form,就像我的第一个表单的右边缘一样。我怎么能这样做?

namespace testing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form = new Form2();
            form.Show();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您需要对MoveResize事件进行编码以适应其他形式。如果两者都能够移动,总是粘在一起,则需要为两者编写事件代码;尽量不创造无限循环;-)

以下是一个例子:

private void Form1_Move(object sender, EventArgs e)
{
   // you may or may not need this flag
   // you would set and clear in the form's constructor and at the end of the Load event.
    if (loading) return; 
    placeForm2();
}

private void Form1_Resize(object sender, EventArgs e)
{
    placeForm2();
}

public void placeForm2()
{
    form2.Top = this.Top;
    form2.Left = this.Left + this.Width;

    int sw = Screen.FromControl(this).WorkingArea.Width;
    int sh = Screen.FromControl(this).WorkingArea.Height;

    if (form2.Right >= sw) form2.Left = this.Left - form2.Width;
    if (form2.Bottom >= sh) form2.Top = sh - form2.Height;
}

只需将placeForm2功能的一个电话添加到您点击按钮的位置..!

注意当您接近右侧屏幕边框时,我如何从左向右移动第二个表格。当然,这是可选的..

答案 1 :(得分:0)

一个简单的解决方案:

private void button1_Click(object sender, EventArgs e)
    {
        int frm1Width = this.Width;
        int frm1Top = this.Top;
        int frm1Left = this.Left;
        int delta = 15;

        Form2 frm2 = new Form2();

        frm2.Show();
        frm2.Top = frm1Top;
        frm2.Left = frm1Left + frm1Width - delta;

    }