WinForm 仅布局实现多个子控件在父控件内水平垂直居中和实现图片按钮效果

参考

环境

软件/系统 版本 说明
Windows windows 10 专业版 22H2 64 位操作系统, 基于 x64 的处理器
Microsoft Visual Studio Community 2022 (64 位) - Current 版本 17.13.6
.NET Framework 4.8

效果预览

  1. 水平居中
    image
  2. 水平与垂直居中
    image

实现子控件在父控件内水平居中

Anchor:None 可以实现类似效果,但不推荐

  1. 添加 tableLayoutPanel1,设置 Anchor: "Top,Left,Right"。(Top非必须项目)
    image
  2. tableLayoutPanel1 设置为1行、三列,其中第1、3列的宽度为百分比: 100%,第2列的宽度为你实际需要的宽度,我这里使用的绝对:300像素。(到这里其实就实现了子控件在父控件内水平居中,因为第2列就是固定宽度并居中)
    image
  3. 添加 tableLayoutPanel2tableLayoutPanel1,设置Dock:Fill
    image
  4. tableLayoutPanel2 设置为1行、三列,每列宽度为百分比: 33.33%
    image
  5. tableLayoutPanel2的每列拖拽入一个 Button,并给 Button 设置Dock:Fill即可填充,实现居中。

实现子控件在父控件内垂直居中

Anchor:None 可以实现类似效果,但不推荐

实现方式与子控件在父控件内水平居中配置基本一致,需要给tableLayoutPanel1设置三行,将子控件的布局放入第2行、第2列内,第1、3行高度设置为百分比: 100%,第2行的高度设置为你需要的实际宽度即可。
image

实现图片按钮

  1. 添加一个Button按钮。
  2. 设置相关属性如下:
    image
    1. BackgroundImage 指定按钮图片
    2. BackgroundImageLayout:Zoom 指定按钮图片布局
    3. FlatStyle:Flat
    4. FlatAppearance
      1. BorderSize:0 去掉边框
      2. MouseDownBackColor: Transparent 鼠标按下背景为透明
      3. MouseOverBackColor: Transparent 鼠标抬起背景为透明
posted @ 2025-05-16 00:09  夏秋初  阅读(177)  评论(2)    收藏  举报