Mohammad Dayyan
Mohammad Dayyan

Reputation: 22458

StartPosition problem in C#?

I wanna show my WinApp in Center Screen, so I set StartPosition property to CenterScreen but the window doesn't show in center of screen.

What's wrong with it ? Am I missing something?

P.S:
I show the window from a main window and with a button.

Edit:
The code that I'm using to show the window.

Form_CO form_CO = new Form_CO();
void button_CO_Click(object sender, EventArgs e)
{
    try
    {
        //StaticVariables.Form_CO_IsShown is to prevent opening the same multiple windows
        if (!StaticVariables.Form_CO_IsShown)
        {
            form_CO = new Form_CO();
            form_CO.Show();
            StaticVariables.Form_CO_IsShown = true;
        }
        else
        {
            form_CO.WindowState = FormWindowState.Normal;
            form_CO.Activate();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Upvotes: 0

Views: 463

Answers (1)

Hans Passant
Hans Passant

Reputation: 942548

FormStartPosition.CenterScreen can be a problem if the form rescales, adjusting itself to the video DPI setting. Paste this code in your form to fix it:

    protected override void OnLoad(EventArgs e) {
        var scr = Screen.FromPoint(this.Location);
        this.Left = scr.WorkingArea.Left + (scr.WorkingArea.Width - this.Width) / 2;
        this.Top = scr.WorkingArea.Top + (scr.WorkingArea.Height - this.Height) / 2;
        base.OnLoad(e);
    }

Upvotes: 3

Related Questions