Adam Nicholson
Adam Nicholson

Reputation: 1

How do I center at the top of screen in C++ WinForm?

I am trying to center my parent form at the top of the screen but it only shows center-screen and center parent and neither centers at the top of the screen. When I tried Google it provided me with plenty of results containing topmost but I have no interest in the topmost functionality I want it top of the screen as in position 0 not as in above all windows and I and unable to locate correct parameters.

Has anyone come across a method for this?

Upvotes: 0

Views: 1766

Answers (2)

Steven P
Steven P

Reputation: 1996

Here's a method to do it:

public static class FormExtensions
{
    public static void CentreTop(this Form form)
    {
        form.Location = new Point((Screen.PrimaryScreen.Bounds.Width - form.Width) / 2, 0);
    }
}

and used in context:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            this.StartPosition = FormStartPosition.Manual;

            this.Resize += Reposition;
            this.Move += Reposition;
        }

        private void Reposition(object sender, EventArgs e)
        {
            this.CentreTop();      
        } 
    }

You may like to add some logic about which screen to centre to if you don't want to always use the PrimaryScreen.

Upvotes: 0

AVIDeveloper
AVIDeveloper

Reputation: 3476

You'll need to use Location property of a Form.

Here's a simple example that will shift a form up to Y = 0:

void Form1_Load( object sender, EventArgs e )
{
    this.Location = new Point( this.Location.X, 0 );
}

Edit: Here's an example the will make sure the form is also centralized at the top of the screen.

void Form1_Load( object sender, EventArgs e )
{
    int x = (Screen.PrimaryScreen.Bounds.Width - this.Width) / 2;
    this.Location = new Point( x, 0 );
}

Note:

  • This example is for a C# WinForm.
  • The reason I'm mentioning it is because your title refers to C++ and WinForms, which don't mix.
    Either you're referring to C# WinForms, or to C++/CLI WinForms (I'll assume you didn't mean C++ MFC Form).

Upvotes: 1

Related Questions