Search code examples
c#winformsposition

Position form where the last form used was positioned


Let's say I have 2 movable forms and when I click a button in one form (the fist one which has it's start position CenterScreen) it brings me to another one (but the second one has still centerscreen start position) and let's say I move the first form before I press the button and when I click the button I want to position the new form where I moved my first form... how can I do this?


Solution

  • use this following code, set StartupPosition = Manual then the Left and Top values (Location) set via the this code

    Code for the Form1

    using System;
    using System.Windows.Forms;
    namespace PositioningCs
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void myButton_Click(object sender, EventArgs e)
            {
                Form2 frm2=new Form2();
                frm2.setLocation(this.Top,this.Left);
                frm2.show();
            }
        }
    }
    

    Code for the Form2

    using System;
    using System.Windows.Forms;
    namespace PositioningCs
    {
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
            private int top_val=0;
            private int left_val=0;
            public void setLocation(int top_val,int left_val)
            {
                  this.top_val=top_val;
                  this.left_val=left_val;
            }
            private void Form2_Load(object sender, EventArgs e)
            {
                this.Top = top_val;
                this.Left = left_val;
            }
        }
    }