C# window positioning

混江龙づ霸主 提交于 2019-11-29 10:04:05

Usually a WinForm is positioned on the screen according to the StartupPosition property.
This means that after exiting from the constructor of Form1 the Window Manager build the window and position it according to that property.
If you set StartupPosition = Manual then the Left and Top values (Location) set via the designer will be aknowledged.
See MSDN for the StartupPosition and also for the FormStartPosition enum.

Of course this remove the need to use this.Handle. (I suppose that referencing that property you are forcing the windows manager to build immediatly the form using the designer values in StartupPosition)

public Form1()
{
    InitializeComponent();
    Load += Form1_Load;
}

void Form1_Load(object sender, EventArgs e)
{
    Location = new Point(700, 20);
}

Or:

public Form1()
{
    InitializeComponent();
    StartPosition = FormStartPosition.Manual;
    Location = new Point(700, 20);
}

Not very sure about the reason, but if you add the positioning code on the Form_Load event it will work as expected without the need to explicitly initialize the handler.

using System;
using System.Windows.Forms;

namespace PositioningCs
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            /*
            IntPtr h = this.Handle;
            this.Top = 0;
            this.Left = 0;
            */
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Top = 0;
            this.Left = 0;
        }
    }
}

You can set the location on form load event like this. this is automatically Handle the Form position.

this.Location = new Point(0, 0); // or any value to set the location
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!