准备工作:
1. 首先,打开vs.net,新建一个C#类库项目。如叫 IpBoxControl。
2. 在vs.net 的菜单,“项目”,“添加用户控件”,把这个用户控件取名为IpBox。
3. 把一个Panel从工具箱拖到IpBox的设计视图,取名为panel1,设置panel1的Location为(0,0),Size为(136, 20),BorderStyle为Fixed3D,BackColor为Window。
4. 把一个TextBox从工具箱拖到panel1里。取名为textBox1,设置textBox1的Location为(8,0),Size为(20, 14),BorderStyle为None,MaxLength为3,TextAlign为Center,Text为““,BackColor为Window。
5. 把一个Label从工具箱拖到panel1里。取名为label1,设置label1的Location为(32, 0),Size为(8, 14),BorderStyle为None,TextAlign为TopCenter,Text为“.”,BackColor为Window。
6. 选取textBox1和label1,textBox1复制、粘贴上3份,label1复制、粘贴上2份。分别命名为textBox2、label2,textBox3、label3,textBox4。Location分别为(40, 0)、(64, 0)、(72, 0)、(96, 0)、(104, 0)。
7. 设置IpBox的Location为(0,0),Size为(136, 20)。
现在一个ip box 的形状已经出来了,接下来要在程序里实现输入的控制。
源代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace XRascal.Controls
{
/// <summary>
/// UserControl1 的摘要说明。
/// </summary>
[
Description("横刀夺爱的 Ip Box 控件!用于输入 IP 地址。"),
ToolboxBitmap(typeof(XRascal.Controls.IpBox))
]
public class IpBox : System.Windows.Forms.UserControl
{
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TextBox textBox4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private string _text = "";
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public IpBox()
{
// 该调用是 Windows.Forms 窗体设计器所必需的。
InitializeComponent();
// TODO: 在 InitializeComponent 调用后添加任何初始化
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器
/// 修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.textBox4 = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();

本文介绍了如何在C#中创建一个自定义的IP地址输入控件 IpBox。通过设计和编程,实现了对用户输入的控制,确保输入的IP地址符合正确格式,并提供了验证和焦点切换功能。
8861

被折叠的 条评论
为什么被折叠?



