C#窗口定位

使用Windows窗体我想将窗口定位到特定的坐标。 我认为它可以用一种简单的方式完成,但是下面的代码根本不起作用:

public Form1() { InitializeComponent(); this.Top = 0; this.Left = 0; } 

但是,当只获得该窗口的句柄时,它运行良好:

 public Form1() { InitializeComponent(); IntPtr hwnd = this.Handle; this.Top = 0; this.Left = 0; } 

您可以看到我根本不使用该指针。 我在MSDN上发现以下声明:

Handle属性的值是Windows HWND。 如果尚未创建句柄,则引用此属性将强制创建句柄。

这是否意味着我们只能在创建句柄后设置窗口位置? 是否在内部使用此手柄设置了顶部/左侧? 谢谢你的澄清。

通常,WinForm根据StartupPosition属性定位在屏幕上。
这意味着在退出Form1的构造函数后,Window Manager构建窗口并根据该属性定位它。
如果设置StartupPosition = Manual,那么通过设计器设置的Left和Top值(Location)将是已知的。
有关 StartupPosition以及FormStartPosition枚举的信息, 请参阅MSDN 。

当然这不需要使用this.Handlethis.Handle 。 (我想引用那个属性你强迫windows管理器使用StartupPosition中的设计器值立即构建表单)

 public Form1() { InitializeComponent(); Load += Form1_Load; } void Form1_Load(object sender, EventArgs e) { Location = new Point(700, 20); } 

要么:

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

不太确定原因,但如果在Form_Load事件上添加定位代码,它将按预期工作,而无需显式初始化处理程序。

 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; } } } 

您可以像这样在表单加载事件上设置位置。 这是自动处理表单位置。

 this.Location = new Point(0, 0); // or any value to set the location