• c# 自定义控件使其填充方格且自动变换大小


     1 using System;
    2 using System.Collections.Generic;
    3 using System.ComponentModel;
    4 using System.Drawing;
    5 using System.Data;
    6 using System.Linq;
    7 using System.Text;
    8 using System.Windows.Forms;
    9
    10 namespace 方格练习
    11 {
    12 public partial class FillBtn : UserControl
    13 {
    14 public FillBtn()
    15 {
    16 InitializeComponent();
    17 }
    18 /// <summary>
    19 /// 填充按钮
    20 /// </summary>
    21 /// <param name="btnNum">按钮数量</param>
    22 public void FillButton(int btnNum)
    23 {
    24 //填充btnNum*btnNum个方格,现在放置的是罗列着的
    25 for (int i = 0; i < btnNum * btnNum; i++)
    26 {
    27 Button btn = new Button();
    28 this.Controls.Add(btn);
    29 }
    30 //定义方法,因为需要改变大小,所以单独
    31 this.LayoutBtns();
    32 }
    33 /// <summary>
    34 /// 布局按钮
    35 /// </summary>
    36 /// <returns></returns>
    37 private void LayoutBtns()
    38 {
    39 //去除启动状态,以免开启的时候FillBtn_SizeChanged会报错
    40 if (this.Controls.Count==0)
    41 {
    42 return;
    43 }
    44 //循环多少次?计算出来
    45 int btnLineNum = (int)Math.Sqrt(this.Controls.Count);
    46 //计算按钮的宽度
    47 int btnWidth = this.Width / btnLineNum;
    48 int btnHeight = this.Height / btnLineNum;
    49
    50 int btnIndex = 0;
    51 int btnX = 0, btnY = 0;
    52 //竖向的循环嵌套横着的循环
    53 for (int verticalIndex = 0; verticalIndex < btnLineNum; verticalIndex++)
    54 {
    55 btnY = verticalIndex * btnHeight;
    56 //水平向的循环
    57 for (int horizontalIndex = 0; horizontalIndex < btnLineNum; horizontalIndex++)
    58 {
    59 btnX = horizontalIndex * btnWidth;
    60 //获取要放置的方格
    61 Button btn = this.Controls[btnIndex] as Button;
    62 //设置当前方格的大小
    63 btn.Size = new Size(btnWidth, btnHeight);
    64 //设置当前方格的位置
    65 btn.Location = new Point(btnX, btnY);
    66 //下一个方格
    67 btnIndex++;
    68 }
    69 }
    70 }
    71
    72 private void FillBtn_SizeChanged(object sender, EventArgs e)
    73 {
    74 //设置当控件大小改变时的事件
    75 this.LayoutBtns();
    76 }
    77 }
    78 }
  • 相关阅读:
    2019-08-10T12:18:27.745963Z 7 [Note] Slave I/O thread for channel '': connected to master 'repl_user@192.168.43.81:3306',replication started in log 'mysql-bin.000001' at position 154 2019-08-10T12:18:
    yum安装的mysql 目录结构
    Starting MySQL.. ERROR! The server quit without updating PID file (/db/data/110.pid).
    CentOS7修改主机名
    使用ssh登陆远程主机
    traceroute命令
    Linux设置开机启动
    检查是否安装服务包
    CSS之盒子模型
    BFC块级格式化上下文
  • 原文地址:https://www.cnblogs.com/dyee/p/2307270.html
Copyright © 2020-2023  润新知