¿Cómo centro una ventana en pantalla en C#?


Necesito una forma de centrar la ventana actual. Por ejemplo, si un usuario presiona un botón, quiero que la ventana se centre en pantalla. Sé que puede usar la propiedad startposition, pero no puedo encontrar una manera de usarla que no sea cuando la aplicación se inicia por primera vez. Entonces, ¿cómo centro el formulario en la pantalla?

Author: Peter Mortensen, 2011-01-05

10 answers

Utilice el formulario .Método CenterToScreen () .

 165
Author: dzendras,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-12 04:25:08
  1. Usando la propiedad ventana

    Seleccione formulario → vaya a ventana de propiedades → seleccione "posición de inicio" → seleccione el lugar que desee.

    "

  2. Mediante programación

    Form form1 = new Form(); form1.StartPosition = FormStartPosition.CenterScreen; form1.ShowDialog();

    Nota: No llame directamente al Formulario.CenterToScreen() de tu código. Lee aquí.

 113
Author: Nayana Adassuriya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-09 02:37:36

Una sola línea:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
 27
Author: harveyt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-10 16:22:08

En Windows Forms:

this.StartPosition = FormStartPosition.CenterScreen;

En WPF:

this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

Eso es todo lo que tienes que hacer...

 25
Author: Saimon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-22 17:09:00

Si desea centrar su windows durante el tiempo de ejecución, use el código a continuación, cópielo en su aplicación:

protected void ReallyCenterToScreen()
{
  Screen screen = Screen.FromControl(this);

  Rectangle workingArea = screen.WorkingArea;
  this.Location = new Point() {
    X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
    Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)};
}

Y finalmente llame al método anterior para que funcione:

ReallyCenterToScreen();
 15
Author: Sarsur.A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-21 15:04:35

Centrar un formulario en tiempo de ejecución

1.Establecer la siguiente propiedad del Formulario:
- > Posición de inicio: CenterScreen
- > WindowState: Normal

Esto centrará el formulario en tiempo de ejecución, pero si el tamaño del formulario es más grande de lo esperado, haga el segundo paso.

2. Agregar Tamaño personalizado después de InitializeComponent ();

public Form1()
{
    InitializeComponent();
    this.Size = new Size(800, 600);
}
 8
Author: Faiz Siddiqui,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-11 04:58:02
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace centrewindow
{
    public partial class Form1 : Form
    {
        public struct RECT
        {
            public int Left;        // x position of upper-left corner
            public int Top;         // y position of upper-left corner
            public int Right;       // x position of lower-right corner
            public int Bottom;      // y position of lower-right corner
        }

        [DllImport("user32.dll")]
        public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);

        [DllImport("user32.dll")]
        public static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CentreWindow(Handle, GetMonitorDimensions());
        }

        private void CentreWindow(IntPtr handle, Size monitorDimensions)
        {
            RECT rect;
            GetWindowRect(new HandleRef(this, handle), out rect);

            var x1Pos = monitorDimensions.Width/2 - (rect.Right - rect.Left)/2;
            var x2Pos = rect.Right - rect.Left;
            var y1Pos = monitorDimensions.Height/2 - (rect.Bottom - rect.Top)/2;
            var y2Pos = rect.Bottom - rect.Top;

            SetWindowPos(handle, 0, x1Pos, y1Pos, x2Pos, y2Pos, 0);
        }

        private Size GetMonitorDimensions()
        {
            return SystemInformation.PrimaryMonitorSize;
        }
    }
}

Centra cualquier ventana de la que puedas obtener el identificador de

 6
Author: Rob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-05 08:14:54

Utilice la propiedad Location del formulario. Colóquelo en el punto superior izquierdo deseado

Deseado x = (desktop_width - form_witdh) / 2

Deseado y =(desktop_height-from_height) / 2

 2
Author: Sarwar Erfan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-05 07:59:03

Usa esto:

this.CenterToScreen();  // This will take care of the current form
 2
Author: UJS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-22 17:13:02

Puede usar el Screen.PrimaryScreen.Bounds para recuperar el tamaño del monitor primario (o inspeccionar el objeto Screen para recuperar todos los monitores). Usa los que tienen MyForms.Bounds para averiguar dónde colocar tu formulario.

 1
Author: C.Evenhuis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-05 07:57:04