C#怎么设置子窗体在主窗体中居中显示

C#怎么设置子窗体在主窗体中居中显示
问题的开始是由C#传传看主群里的 印醒 提出来的,下面我来说一下解决方案吧
其实表面上看是很简单的
开始吧,现在有两个窗体Form1主窗体,Form2子窗体
而且我相信大部分人都会这样写
在子窗体的Load事件中
这样写
[code=csharp] this.StartPosition = FormStartPosition.CenterParent;[/code]
其实这样写是不对的,正确的写法应该是
[code=csharp] this.StartPosition = FormStartPosition.CenterScreen;[/code]
为什么是CenterScreen而不是CenterParent呢?
那是因为我们调用的方法的问题,如果你在调用子窗体时是这样写的话
[code=csharp] Form2 f2 = new Form2();
            f2.MdiParent  = this;
            f2.Show();[/code]
那就得使用CenterScreen而不是CenterParent了,因为在Show的时候窗体是Owner页不是Parent
只要使用ShowDialog()方法时使用CenterParent才有效
大家会说这样就行了吗?其实也不行,我们的代码不应该写在Load事件中,而是在Show方法之前写。
正确的写法应该是这样的
[code=csharp] Form2 f2 = new Form2();
            f2.MdiParent  = this;
            f2.StartPosition = FormStartPosition.CenterScreen;
            f2.Show();[/code]
而在子窗体中你什么也不需要做
效果如下
 
再提供一个布局的其实属性
StartPosition属性有如下选项,分别含义如下:
  CenterParent                     窗体在其父窗体中居中。    
  CenterScreen                     窗体在当前显示窗口中居中,其尺寸在窗体大小中指定。    
  Manual                           窗体的位置由   Location   属性确定。    
  WindowsDefaultBounds     窗体定位在   Windows   默认位置,其边界也由   Windows   默认决定。    
  WindowsDefaultLocation    窗体定位在   Windows   默认位置,其尺寸在窗体大小中指定。     
    

   CenterScreen的意思并不是屏幕居中(是相对的),它是在"当前显示窗口"中居中。

转自:http://www.sufeinet.com/thread-1473-1-1.html

猜你喜欢

转载自blog.csdn.net/lbc2100/article/details/80855867