12

使用 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。如果尚未创建句柄,则引用此属性将强制创建句柄。

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

4

4 回答 4

10

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 builds the window and positions 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 immediately the form using the designer values in StartupPosition)

于 2012-04-26T09:20:41.410 回答
5
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);
}
于 2012-04-26T12:03:57.037 回答
4

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

this.Location = new Point(0, 0); // or any value to set the location
于 2016-01-22T04:54:31.830 回答
3

不太确定原因,但如果您在 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;
        }
    }
}
于 2012-04-26T09:30:27.500 回答