Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

winforms - C# window positioning

Using Windows Forms I wanted to position window into specific coords. I thought it can be done in a simple way, but following code does not work at all:

public Form1()
{
    InitializeComponent();

    this.Top = 0;
    this.Left = 0;
}

However, when only get a handle to that window, it works well:

public Form1()
{
    InitializeComponent();

    IntPtr hwnd = this.Handle;
    this.Top = 0;
    this.Left = 0;
}

You can see that I am not working with that pointer at all. I found at MSDN following statement:

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.

Does it mean that we can set window position only AFTER the creation of its handle? Are setters Top/Left using this handle internally? Thank you for clarification.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...