如何在 C# 和 C# 中使窗口在屏幕上居中WinForms?

发布于 2024-10-10 09:27:10 字数 146 浏览 0 评论 0 原文

我需要一种方法使当前窗口在屏幕上居中。

例如,如果用户按下按钮,我希望窗口在屏幕上居中。

我知道您可以使用 startposition 属性,但除了应用程序首次启动时之外,我无法找到使用该属性的方法。

那么如何使表单在​​屏幕上居中呢?

I need a way to center the current window on the screen.

So for example, if a user pushes a button, I want the window to center itself on the screen.

I know you can use the startposition property, but I cannot figure out a way to use that other than when the application first starts up.

So how do I center the form on the screen?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

陌上青苔 2024-10-17 09:27:10
  1. 使用属性窗口

    选择表格→进入属性窗口→选择“起始位置”→选择你想要的位置。

  2. 以编程方式

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

    注意:不要直接从代码中调用 Form.CenterToScreen()。请阅读此处

  1. Using the Property window

    Select form → go to property window → select "start position" → select whatever the place you want.

    "

  2. Programmatically

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

    Note: Do not directly call Form.CenterToScreen() from your code. Read here.

酒中人 2024-10-17 09:27:10

单行:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);

A single line:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
绿阴红影里的.如风往事 2024-10-17 09:27:10

在 Windows 窗体中:

this.StartPosition = FormStartPosition.CenterScreen;

在 WPF 中:

this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

这就是您所要做的...

In Windows Forms:

this.StartPosition = FormStartPosition.CenterScreen;

In WPF:

this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

That's all you have to do...

无所的.畏惧 2024-10-17 09:27:10

如果您想在运行时将窗口居中,请使用下面的代码,将其复制到您的应用程序中:

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)};
}

最后调用上面的方法使其工作:

ReallyCenterToScreen();

If you want to center your windows during runtime use the code below, copy it into your application:

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)};
}

And finally call the method above to get it working:

ReallyCenterToScreen();
岁月静好 2024-10-17 09:27:10

 在运行时居中表单

1.设置Form的以下属性:

   ->开始位置:屏幕中心

   -> WindowState: Normal

这将使窗体在运行时居中,但如果窗体大小大于预期,请执行第二步。

2.在InitializeComponent()之后添加自定义Size;

public Form1()
{
    InitializeComponent();
    this.Size = new Size(800, 600);
}

 Centering a form in runtime

1.Set following property of Form:

   -> StartPosition : CenterScreen

   -> WindowState: Normal

This will center the form at runtime but if form size is bigger then expected, do second step.

2. Add Custom Size after InitializeComponent();

public Form1()
{
    InitializeComponent();
    this.Size = new Size(800, 600);
}
叹沉浮 2024-10-17 09:27:10

使用这个:

this.CenterToScreen();  // This will take care of the current form

Use this:

this.CenterToScreen();  // This will take care of the current form
原来是傀儡 2024-10-17 09:27:10
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;
        }
    }
}

将您可以控制的任何窗口居中

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;
        }
    }
}

Centers any window you can get the handle of

天冷不及心凉 2024-10-17 09:27:10

可能与问题不完全相关。但也许可以帮助某人。

中心屏幕以上对我来说都不起作用。原因是我正在向表单动态添加控件。从技术上讲,当它居中时,它是正确的,基于添加控件之前的表单。

这是我的解决方案。 (应该适用于这两种情况)

int x = Screen.PrimaryScreen.Bounds.Width - this.PreferredSize.Width;
int y = Screen.PrimaryScreen.Bounds.Height - this.PreferredSize.Height;

this.Location = new Point(x / 2, y / 2);

所以您会注意到我使用“PreferredSize”而不是仅使用高度/宽度。
添加控件后,首选大小将保留表单的值。高度/宽度不会的地方。

希望这对某人有帮助。

干杯

Might not be completely relevant to the question. But maybe can help someone.

Center Screen non of the above work for me. Reason was I was adding controls dynamically to the form. Technically when it centered it was correct , based on the form before adding the controls.

So here was my solution. ( Should work with both scenarios )

int x = Screen.PrimaryScreen.Bounds.Width - this.PreferredSize.Width;
int y = Screen.PrimaryScreen.Bounds.Height - this.PreferredSize.Height;

this.Location = new Point(x / 2, y / 2);

So you will notice that I am using "PreferredSize" instead of just using Height / Width.
The preferred size will hold the value of the form after adding the controls. Where Height / Width won't.

Hope this helps someone .

Cheers

祁梦 2024-10-17 09:27:10

工作样本

private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
    AccountAddForm f = new AccountAddForm();
    f.StartPosition = FormStartPosition.CenterScreen;
    f.Show();            
}

Working sample

private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
    AccountAddForm f = new AccountAddForm();
    f.StartPosition = FormStartPosition.CenterScreen;
    f.Show();            
}
音盲 2024-10-17 09:27:10

使用表单的 Location 属性。将其设置为所需的左上角点

所需的 x = (desktop_width - form_witdh)/2

所需的 y = (desktop_height - from_height)/2

Use Location property of the form. Set it to the desired top left point

desired x = (desktop_width - form_witdh)/2

desired y = (desktop_height - from_height)/2

近箐 2024-10-17 09:27:10

您可以使用 Screen.PrimaryScreen.Bounds 来检索主显示器的大小(或检查 Screen 对象来检索所有显示器)。使用 MyForms.Bounds 来确定放置表单的位置。

You can use the Screen.PrimaryScreen.Bounds to retrieve the size of the primary monitor (or inspect the Screen object to retrieve all monitors). Use those with MyForms.Bounds to figure out where to place your form.

稀香 2024-10-17 09:27:10

在多显示器的情况下,如果您喜欢在正确的显示器/屏幕上居中,那么您可能想尝试以下几行:

// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;

// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;

In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:

// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;

// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文