0

无论主窗体是最大化还是正常大小,我都试图在主窗体的右上角打开一个(未装饰的)子窗体。但是无论我如何尝试,我都无法将其打开到我想要的位置。

我发现一篇文章描述了如何相对于表单中的另一个控件打开表单,但这也不起作用:

如何在相对于父窗口中的控件的位置显示模态表单(打开器)

现在已经尝试在 google 上搜索几个小时以寻找解决方案,但要么没有答案(doubdfull),要么我没有在搜索紧密的单词组合(更有可能)。

任何人都可以请我指出一个类似的问题,或者帮助我如何实现我所希望的吗?

4

3 回答 3

2

在我看来,您应该使用锚定在顶部和右侧的 UserControl。但是,让我们制作一个表格。您需要连接它的 Load 事件,以便在它重新调整自身后将其移动到正确的位置。然后您需要主窗体的 LocationChanged 和 Resize 事件,以便您可以将子窗体保持在正确的位置。

因此,具有样板 Form1 和 Form2 名称以及 Form1 上用于显示子项的按钮的示例程序可能如下所示:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.button1.Click += button1_Click;
        this.Resize += this.Form1_Resize;
        this.LocationChanged += this.Form1_LocationChanged;

    }

    Form child;

    private void button1_Click(object sender, EventArgs e) {
        if (child != null) return;
        child = new Form2();
        child.FormClosed += child_FormClosed;
        child.Load += child_Load;
        child.Show(this);
    }

    void child_FormClosed(object sender, FormClosedEventArgs e) {
        child.FormClosed -= child_FormClosed;
        child.Load -= child_Load;
        child = null;
    }

    void child_Load(object sender, EventArgs e) {
        moveChild();
    }

    void moveChild() {
        child.Location = this.PointToScreen(new Point(this.ClientSize.Width - child.Width, 0));
    }

    private void Form1_Resize(object sender, EventArgs e) {
        if (child != null) moveChild();
    }

    private void Form1_LocationChanged(object sender, EventArgs e) {
        if (child != null) moveChild();
    }

}
于 2012-07-21T19:00:21.050 回答
0

尝试这样的事情:

 private void button1_Click(object sender, EventArgs e)
        {
            ChildForm win = new ChildForm();
            int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
            int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;

            Point parentPoint = this.Location;

            int parentHeight = this.Height;
            int parentWidth = this.Width;

            int childHeight = win.Height;
            int childWidth = win.Width;

            int resultX = 0;
            int resultY = 0;

            if ((parentPoint.X + parentWidth + childWidth) > screenWidth)
            {
                resultY = parentPoint.Y;
                resultX = parentPoint.X - childWidth;
            }
            else
            {
                resultY = parentPoint.Y;
                resultX = parentPoint.X + parentWidth;
            }

            win.StartPosition = FormStartPosition.Manual;                   
            win.Location = new Point(resultX, resultY);  
            win.Show();
        }
于 2012-07-21T18:49:02.150 回答
0

我认为你应该尝试这样的事情:

private void buttonOpen_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.Show();
    //"this" is the parent form
    frm2.DesktopLocation = new Point(this.DesktopLocation.X + this.Width - frm2.Width, this.DesktopLocation.Y);
}

简单、容易且有效(对我而言)。

于 2012-07-21T19:04:59.643 回答