How to center GameWindow?

Hey guys. Main question - How do I center the GameWindow? I’ve looked online and I can only seem to find unrelated answers. When I run the program, I want the GameWindow to be in the center of the monitor. I looked up the GameWindow class for XNA and some other things too, but I can’t seem to find anything that alludes to changing the GameWindow position.

I know how to resize the GameWindow:

   graphics.PreferredBackBufferWidth = screenWidth; // +Height

I also know how to offset the GameWindow relative to the System.Windows.Form:

    // After adding references System.Windows.Forms and System.Drawing:
    var form = (System.Windows.Forms.Form)System.Windows.Forms.Control.FromHandle(this.Window.Handle);
    form.Location = new System.Drawing.Point(xOffset, yOffset);

Also, as a side question: How do I get the current screen resolution of the graphics card? I’ve been able to center my GameWindow the hard way using offset arithmetic, but that assumes that I know what the screen resolution is. I want my game to adjust itself to the end users screen resolution (when not in Full Screen mode, as I assume Full Screen mode does this automatically?).

Thanks for any help.

this one?

graphics.GraphicsDevice.Adapter.CurrentDisplayMode

2 Likes

Thanks, I went to MSDN with your line and found a nice way to implement it. I got the code to work and I’ll be testing it with various things tomorrow.

Thanks for the help.

I don’t think XNA has/had it but in Monogame, the GameWindow class has a “Position” property to set the windows position. For example, in your Game class :

this.Window.Position = new Point(200, 50); // xPos and yPos (pixel)

I think it sets the position of the top-left corner of the window so if you know your window size and your screen size, you can find the top-left position that makes the window centered :wink:

Though it is a Windows-only feature according to the source code : https://github.com/MonoGame/MonoGame/blob/develop/MonoGame.Framework/GameWindow.cs

@Madolite The window should be centered by default. If you’re using the develop branch and the gamewindow is not centered without you setting the Position you can open an issue on GitHub.

It isn’t centered for me neither on windows7pro

Easy use code

Window.Position = new Point((GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width / 2) - (graphics.PreferredBackBufferWidth / 2), (GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height / 2) - (graphics.PreferredBackBufferHeight / 2));

It is center of screen.

I hope my code helps you

4 Likes