C# WinForm实现Form表单自定义
|
admin
2025年3月22日 7:49
本文热度 1430
|


using System;using System.Collections;using System.Collections.Generic;using System.ComponentModel;using System.ComponentModel.Design;using System.ComponentModel.Design.Serialization;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Web.UI.Design.WebControls;using System.Windows.Forms;using YUTU.UIL.Common.Controls;
namespace WindowsFormsApp1{ public partial class Form3 : Form { public Form3() { InitializeComponent(); }
private void Form3_Load(object sender, EventArgs e) { initDesign(); loadVisibleControl(); }
DesignSurface surface; IDesignerHost host; Control root;
private void initDesign() { surface = new DesignSurface(); surface.BeginLoad(typeof(UserControl));
Control designView = surface.View as Control; panel1.Controls.Add(designView); designView.Dock = DockStyle.Fill; designView.Visible = true;
host = (IDesignerHost)surface.GetService(typeof(IDesignerHost)); root = (Control)host.RootComponent; root.Dock = DockStyle.Fill;
ISelectionService selectionService = host.GetService(typeof(ISelectionService)) as ISelectionService; selectionService.SelectionChanged += delegate { try { ICollection collection = selectionService.GetSelectedComponents(); if (collection.Count > 0) { foreach (Control item in collection) { label1.Text = "X:" + item.Location.X.ToString(); label2.Text = "Y:" + item.Location.Y.ToString(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }; }
public void loadVisibleControl() {
TextBoxEx tbe = (TextBoxEx)host.CreateComponent(typeof(TextBoxEx), "name"); tbe.LabelText = "姓名"; root.Controls.Add(tbe);
TextBoxEx tbe1 = (TextBoxEx)host.CreateComponent(typeof(TextBoxEx), "class"); tbe1.LabelText = "班级"; root.Controls.Add(tbe1);
TextBoxEx tbe2 = (TextBoxEx)host.CreateComponent(typeof(TextBoxEx), "age"); tbe2.LabelText = "年龄"; root.Controls.Add(tbe2);
}
}}
阅读原文:原文链接
该文章在 2025/3/24 13:21:49 编辑过