C # window positioning

Using Windows Forms, I wanted to put the window at specific coordinates. I thought this could be done in a simple way, but the following code does not work at all:

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

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

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

You can see that I do not work with this pointer at all. I found the following statement on MSDN:

The value of the Handle property is Windows HWND. If the handle has not yet been created, a reference to this property will force the handle to be created.

Does this mean that we can set the position of the window only after creating its handle? Do the upper / left setters set with this handle inside? Thank you for your clarification.

+6
source share
4 answers

Typically, a WinForm is placed on the screen according to the StartupPosition property. This means that after exiting the Form1 constructor, Window Manager will close the window and place it according to this property.
If you set StartupPosition = Manual , then the Left and Top (Location) values ​​set through the constructor will be recognized.
See MSDN for StartupPosition as well as for FormStartPosition ENUM.

Of course, this eliminates the need to use this.Handle . (I believe that by referring to this property, you force the window manager to directly create the form using the constructor values ​​in StartupPosition)

+5
source
 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); } 
+4
source

Not very sure of the reason, but if you add the positioning code to the Form_Load event, it will work as expected, without having 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; } } } 
+3
source

You can set the location in the form load event as follows. It automatically handle the position of the form.

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

Source: https://habr.com/ru/post/914202/


All Articles