我想使用 Windows 窗体将窗口定位到特定的坐标中。我认为这可以用一种简单的方式完成,但是下面的代码根本不起作用:
public Form1()
{
InitializeComponent();
this.Top = 0;
this.Left = 0;
}
但是,当只获取那个窗口的句柄时,它工作得很好:
public Form1()
{
InitializeComponent();
IntPtr hwnd = this.Handle;
this.Top = 0;
this.Left = 0;
}
你可以看到我根本没有使用那个指针。我在 MSDN 上找到以下声明:
The value of the Handle property is a Windows HWND. If the handle has not yet been created, referencing this property will force the handle to be created.
这是否意味着我们只能在创建其句柄后才能设置窗口位置? setter Top/Left 是否在内部使用此 handle ?感谢您的澄清。
最佳答案
通常根据 StartupPosition 属性将 WinForm 定位在屏幕上。
这意味着从 Form1 的构造函数退出后,窗口管理器构建窗口并根据该属性定位它。
如果您设置 StartupPosition = Manual,那么通过设计器设置的 Left 和 Top 值(位置)将被识别。
See MSDN对于 StartupPosition 和 FormStartPosition枚举。
当然,这消除了使用 this.Handle
的需要。
(我想引用该属性是在强制 Windows 管理器使用 StartupPosition 中的设计器值立即构建表单)
关于C#窗口定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10330470/