winform panel动态添加textbox控件

发布时间 2023-04-20 09:22:06作者: 你像风
        //控件宽高
        int control_w = 159;
        int control_h = 55;
        //间隔距离
        int interval_x = 20;
        int interval_y = 20;
        //列可放置数量
        int row_count = 3;

        /// <summary>
        /// 动态加载人员选择框
        /// </summary>
        /// <param name="list"></param>
        public void LoadNameTextBox(List<PersonInformation> list)
        {
            //容器宽高 562 559
            int panel_w = pnlPerson.Width;
            int panel_h = pnlPerson.Height;
            row_count = panel_w / (control_w + interval_x);

            for (int i = 0; i < list.Count; i++)
            {
                int row = i / row_count;
                int column = i % row_count;

                var t = new TextBox();
                if (list[i].state == "0")
                {
                    t.BackColor = Color.LightGray;
                }
                else
                {
                    t.BackColor = Color.LimeGreen;
                }
                t.BorderStyle = BorderStyle.None;
                t.Font = new Font("宋体", 36F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
                t.ForeColor = Color.White;
                int x = (interval_x * (column + 1)) + (control_w * column);
                int y = (interval_y * (row + 1)) + (control_h * row);
                t.Location = new Point(x, y);
                t.Name = "txt" + list[i].person_id;
                t.Size = new Size(control_w, control_h);
                t.TabIndex = Int32.Parse(list[i].state);
                t.Text = list[i].name;
                t.TextAlign = HorizontalAlignment.Center;
                t.Click += new EventHandler(txt_Click);
                t.MouseDown += new MouseEventHandler(txt_MouseDown);
                t.MouseEnter += new EventHandler(txt_MouseEnter);
                this.pnlPerson.Controls.Add(t);
            }
        }

        void txt_Click(object sender, EventArgs e)
        {
            foreach (Control control in this.pnlPerson.Controls)
            {
                TextBox tb = (TextBox)control;
                if (tb.TabIndex == 0)
                {
                    tb.BackColor = Color.LightGray;
                }
                else
                {
                    tb.BackColor = Color.LimeGreen;
                }
            }
            TextBox txt = (TextBox)sender;
            txt.BackColor = Color.Red;
        }

        [DllImport("user32", EntryPoint = "HideCaret")]
        private static extern bool HideCaret(IntPtr hWnd);

        void txt_MouseDown(object sender, MouseEventArgs e)
        {
            HideCaret(((TextBox)sender).Handle);
        }
        void txt_MouseEnter(object sender, EventArgs e)
        {
            HideCaret(((TextBox)sender).Handle);
        }