Reputation: 35557
I'm trying to adapt @HansPasant's code from vb.net
to c#
. Also I want to adapt it so the winForms
starts centered in terms of top-to-bottom but to the far left of the screen in terms of left-to-right:
vb.net
from here How to set winform start position at top right? :
Public Class Form1
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
Dim scr = Screen.FromPoint(Me.Location)
Me.Location = New Point(scr.WorkingArea.Right - Me.Width, scr.WorkingArea.Top)
MyBase.OnLoad(e)
End Sub
End Class
My current (bad) attempt:
private void scriptSurfer_Load(object sender,EventArgs e)
{
var scr = Screen.FromPoint(this.Location);
this.Location = New Point(scr.WorkingArea.Left - this.Width, scr.WorkingArea.Top);
this.OnLoad(e);
}
Upvotes: 1
Views: 112
Reputation: 216293
If I have understood your question you need
The LeftMost position of the Screen = 0 Vertical Centering = (Screen.Height - form.Height) / 2
this.Location = new Point(0, (scr.WorkingArea.Height - this.Height) / 2);
and do not forget
Form.StartPosition = FormStartPosition.Manual
As noted below in comments, the best point in which execute this code is inside the override of the OnLoad method albeit a Load event should work just fine in 99% of the situations. Also using the Screen.WorkingArea.Left
property to position the form on the left side of the screen could be better instead of a fixed leftmost position. This could avoid edge cases where the leftmost available position is not at zero coordinates.
protected override void OnLoad(EventArgs e)
{
var scr = Screen.PrimaryScreen;
this.Location = new Point(scr.WorkingArea.Left,
(scr.WorkingArea.Height - this.Height) / 2);
base.OnLoad(e);
}
Upvotes: 3