In the Shown event handler, set the Width and Height properties:
Rectangle screen = Screen.FromControl(this).Bounds;
Width = screen.Width;
Height = 200;
[edit]
Hi Luc!
Generally, I use the Load event rather than the constructor - it'll work in the Shown, but lats less efficient as you said.
It's actually really easy: Windows treats multiple monitors as a single large desktop.
So this is my default project startup code:
private void FrmMain_Load(object sender, EventArgs e)
{
if ((ModifierKeys & Keys.Shift) == 0)
{
this.LoadLocation();
}
}
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if ((ModifierKeys & Keys.Shift) == 0)
{
this.SaveLocation();
}
}
...
public static void SaveLocation(this Control control, string instance = null)
{
string controlName = control.GetType().Name;
if (!File.Exists(LocationsStorageFile))
{
CreateBlankLocationFile();
}
if (!(control is Form f) || (f.Visible && f.WindowState == FormWindowState.Normal))
{
DataTable dt = ReadXML(LocationsStorageFile);
if (dt.Columns.Count >= 6)
{
bool ignoreInstance = string.IsNullOrWhiteSpace(instance);
DataRow current = dt.NewRow();
current["ControlName"] = controlName;
current["Instance"] = instance ?? "";
foreach (DataRow row in dt.Rows)
{
if (row["ControlName"] as string == controlName && (ignoreInstance || row["Instance"] as string == instance))
{
dt.Rows.Remove(row);
break;
}
}
current["LocationX"] = control.Location.X;
current["LocationY"] = control.Location.Y;
current["SizeW"] = control.Size.Width;
current["SizeH"] = control.Size.Height;
dt.Rows.Add(current);
WriteXML(dt, LocationsStorageFile);
}
}
}
public static void LoadLocation(this Control control, string instance = null)
{
string controlName = control.GetType().Name;
if (!File.Exists(LocationsStorageFile))
{
CreateBlankLocationFile();
}
DataTable dt = ReadXML(LocationsStorageFile);
if (dt.Columns.Count >= 6)
{
bool ignoreInstance = string.IsNullOrWhiteSpace(instance);
DataRow current = dt.NewRow();
current["ControlName"] = controlName;
current["Instance"] = instance ?? "";
current["LocationX"] = control.Location.X;
current["LocationY"] = control.Location.Y;
current["SizeW"] = control.Size.Width;
current["SizeH"] = control.Size.Height;
foreach (DataRow row in dt.Rows)
{
if (row["ControlName"] as string == controlName && (ignoreInstance || row["Instance"] as string == instance))
{
current = row;
if (int.TryParse(current["LocationX"].ToString(), out int x) &&
int.TryParse(current["LocationY"].ToString(), out int y) &&
int.TryParse(current["SizeW"].ToString(), out int w) &&
int.TryParse(current["SizeH"].ToString(), out int h))
{
control.Location = new Point(x, y);
control.Size = new Size(w, h);
}
break;
}
}
}
}
[/edit]