是否可以在设计时使窗体在Visual Studio WinForms设计器中居中

3qpi33ja  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(404)

我目前正在做一个小程序,它会在超时时自动按下某个按钮,我是用visual studio的windows窗体来做这个程序的,但是这个项目是从visual studio左上角的窗体窗口开始的。
现在,我想让它在视觉本身的中间居中,但我不知道如何居中。
我在谷歌上能找到的就是如何在应用程序启动/执行时将其居中,但正如我提到的,我只希望它集中在视觉本身的工作空间内。
我希望任何人都能帮我解决这个奢侈品问题。
格特让

x7yiwoj4

x7yiwoj41#

在Windows窗体设计器中,在设计时使窗体居中与在运行时使窗体居中不同,它们基本上彼此没有任何关系。
在设计器中居中窗体只是使它出现在VS设计器中工作区的中间。可以使用以下两种方法之一:

  • 借助自定义设计器设置位置
  • 通过一点小技巧,修改基本窗体设计器的位置
  • 处理基窗体及其父窗体的Layout事件,并检查DesignMode属性,而不使用设计器。

基本技巧是根据设计图面(窗体的父级)的大小在设计模式下设置窗体的位置:

在下面的示例中,我使用基窗体并修改设计器位置来处理它。若要创建一个简单的项目来演示该功能,请按照下列步骤操作:
1.创建一个新的WinForms项目(.NET框架),并将其命名为FormDesignerExample
1.添加对“System.Design”程序集的引用。(右键单击,添加引用,在框架程序集中搜索它)。
1.将以下MyBaseForm类添加到项目中:

using System.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design.Behavior;

namespace FormDesignerExample
{
    public class MyBaseForm : Form
    {
        protected override void CreateHandle()
        {
            base.CreateHandle();
            if (Site == null)
                return;
            var host = (IDesignerHost)this.Site.GetService(typeof(IDesignerHost));
            var rootDesigner = (IRootDesigner)host.GetDesigner(host.RootComponent);
            var rootComponent = (Control)rootDesigner.Component;
            var designSurface = rootComponent.Parent;

            rootComponent.Layout += (sender, e) =>
            {
                var left = (designSurface.Width - rootComponent.Width) / 2;
                var top = (designSurface.Height - rootComponent.Height) / 2;
                rootComponent.Location = new Point(left, top);
            };
            designSurface.SizeChanged += (sender, e) =>
            {
                var left = (designSurface.Width - rootComponent.Width) / 2;
                var top = (designSurface.Height - rootComponent.Height) / 2;
                rootComponent.Location = new Point(left, top);
                var bhSvc = (BehaviorService)host
                    .GetService(typeof(BehaviorService));
                bhSvc.SyncSelection();
            };
        }
    }
}

1.打开Form1.cs并从MyBaseForm驱动

public partial class Form1 : MyBaseForm

1.关闭所有设计器窗体,重新生成项目。然后在设计模式下打开Form1。
给你。

相关问题