I have a winforms app with a main form (fMain) and two child forms (fLogin and fAdmin). fLogin is displayed using this code which is in a button click event handler for a button on the main form:
// show login form; pass the main form in as an argument
fLogin formLogin = new fLogin(this);
formLogin.StartPosition = FormStartPosition.CenterParent;
formLogin.ShowDialog(this);
In the constructor for fLogin, I assign the main form to a private member level variable.
// fLogin
fMain _mainForm;
// fLogin constructor
public fLogin(fMain mainForm)
{
InitializeComponent();
_mainForm = mainForm;
}
As you might imagine, fLogin is a small form with textboxes for a username and password and a couple of buttons. When my users enter their credentials and click the OK button, fLogin will validate the information with a server and if the information is good, fLogin will disappear and fAdmin will be displayed. Currently, I'm displaying fAdmin like this:
// hide formLogin right away
this.Hide()
// show admin form
fAdmin formAdmin = new fAdmin();
formAdmin.StartPosition = FormStartPosition.CenterParent;
formAdmin.Show(_mainForm); // pass main form as owner of admin form
// close formLogin
this.Close();
I can't set formAdmin.Parent = _mainForm and get the dialog to magically center itself. So I'm passing _mainForm to formAdmin.Show() as the owner of formAdmin but that doesn't seem to help with regard to getting formAdmin centered. Is there an easy way to cause formAdmin to be displayed at the center of the main form?
I think you need to restructure how you are doing this just a bit, instead of displaying fAdmin from within fLogin, close fLogin and then open fAdmin from fMain. If this doesn't work you can manually center if by calculating the point for the upper left corner of fAdmin and set this point as fAdmin's Location. I've had to do this in the past when I've encountered similar issues. To calculate the upper left corner for fAdmin so that it will be centered on fMain, use the following:
Point p = new Point(0, 0);
p.Y = (fMain.Height / 2) - (fAdmin.Height / 2);
p.X = (fMain.Width / 2) - (fAdmin.Width / 2);
fAdmin.Location = p;