我目前正在制作一个小应用程序,它会在加班时自动为我按下某个按钮。 我用 visual studio 的窗体做这个,但项目从 visual studio 左上角的窗体窗口开始。
现在我想让它在视觉本身的中间居中,但我不知道如何居中。
我在谷歌上只能找到如何在应用程序启动/执行时将其居中。但正如我提到的,我只希望它以视觉本身的工作空间为中心。
我希望有人能帮我解决这个奢侈品问题
Gert-Jan
在自定义设计器的帮助下,或者对设计器进行一些修改,可以在 Visual Studio 内的工作区中将表单居中或基本上在设计器中居中:
诀窍是根据设计表面尺寸的大小设置根组件的位置。
要创建一个简单的项目来演示该功能,请按照以下步骤操作:
创建一个新的 WinForms 项目(.NET Framework),并命名为
FormDesignerExample
.
添加对“System.Design”程序集的引用。 (右键单击,添加引用,在框架程序集中搜索它)。
在项目中添加以下
MyBaseForm
类:
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design.Behavior;
namespace FormDesignerExample
{
public class MyBaseForm : Form
{
protected override void CreateHandle()
{
base.CreateHandle();
var host = (IDesignerHost)this.Site.GetService(typeof(IDesignerHost));
var rootDesigner = (IRootDesigner)host.GetDesigner(host.RootComponent);
var rootComponent = (Control)rootDesigner.Component;
var designSurface = rootComponent.Parent;
designSurface.SizeChanged += (sender, e) =>
{
rootComponent.Left = (designSurface.Width - rootComponent.Width) / 2;
rootComponent.Top = (designSurface.Height - rootComponent.Height) / 2;
((BehaviorService)host.GetService(typeof(BehaviorService))).SyncSelection();
};
}
}
}
打开Form1.cs,从MyBaseForm驱动
public partial class Form1 : MyBaseForm
关闭所有设计器窗体,重建项目。然后在设计模式下打开Form1。
给你。