如何创建一个遮罩文本框接收IP地址输入

本文关键字:文本 IP 输入 地址 一个 何创建 创建 | 更新日期: 2023-09-27 18:11:27

我正在尝试创建一个屏蔽文本框,用于输入类似于IP地址。我不想使用第三方控件,我想开发我自己的。有人能给我指路吗?

我已经设法将键盘输入限制为数字。我如何添加(…)面具?

如何创建一个遮罩文本框接收IP地址输入

****这是一个完美的方式有一个本地Win32控件支持处理IP地址

  public class IPTextBox : TextBox
        {
            public IPTextBox() : base()
            {
            }
            protected override CreateParams CreateParams
            {
                get
                {
                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
                    CreateParams cp = base.CreateParams;
                    cp.ClassName = "SysIPAddress32";
                    return cp;
                }
            }

        }

如果您非常热衷于为相同的控件开发自己的控件。你可能需要处理关键事件,并根据指定的掩码

呈现值。

下面是来自WPF工具箱的一个类似的遮罩文本框

https://wpftoolkit.codeplex.com/SourceControl/latest主要来源/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit/MaskedTextBox/实现/MaskedTextBox.cs

这个链接提供了完整的实现,您可以看看并开发自己的

我很惊讶最近没有什么东西,或者至少是c#中Windows窗体的半体面的东西来解决这个问题,甚至可以在不返回到Windows 3.1语法,cmd, msg, lpcstrs的情况下将其打磨成可维护的东西。导入dll等。

我用4个文本框、3个位图(点)MSDN应用程序注释和一些关键事件处理程序创建了一个控件。拒绝非数字并不难,在插入模式下将文本字符串截断为三个字符也不难,但要找到一种组合,使输入和tab键之间的文本框能够平滑过渡,需要进行一些尝试和错误。让最后一个文本框将焦点转移到窗体中的下一个控件上有点令人沮丧。

与往常一样,tab和enter的处理方式不同,并且在按下键和按下键之间进行操作-我不得不猜测发生了什么,因为我没有任何花哨的步进源库。

无论如何,这是我的解决方案。我昨天写的,今天测试了。我明天有一个演示,祝我好运。
    using System;
using System.Drawing;
using System.Net;
using System.Windows.Forms;
using Framework.UserApplication.Utility;
namespace Framework.UserApplication.CommonDialogs
{
    /**************************************************************************************************
     * A TCP IP input mask.
     * sealed because of virtual member calls in constructor
     *  By having a virtual call in an object's constructor you are introducing the possibility that
     *  inheriting objects will execute code before they have been fully initialized.
     **************************************************************************************************/
    public sealed partial class TcpIpInputMaskType : UserControl
    {
        private bool _hasFocus; // True if this TcpIpInputMaskType has focus
        private IPAddress _ipAddress; // The IP address
        private bool _showFocusRect; // True to show, false to hide the focus rectangle
        /**************************************************************************************************
         * Default constructor.
         **************************************************************************************************/
        public TcpIpInputMaskType()
        {
            _showFocusRect = ShowFocusCues;
            _hasFocus = false;
            InitializeComponent();
            ChangeUICues += IpTextBoxes_ChangeUiCues;
            BackColor = Color.Transparent;
            AutoSize = true;
        }
        /**************************************************************************************************
         * Gets the IP address.
         *
         * @return  The IP address.
         **************************************************************************************************/
        public IPAddress IpAddress
        {
            get
            {
                try
                {
                    _ipAddress = new IPAddress(new[]
                    {
                        Convert.ToByte(IP1.Text), Convert.ToByte(IP2.Text),
                        Convert.ToByte(IP3.Text), Convert.ToByte(IP4.Text)
                    });
                }
                catch (Exception e)
                {
                    _ipAddress = null;
                    Console.WriteLine(e);
                }
                return _ipAddress;
            }
        }
        /**************************************************************************************************
         * Gets the IP address hex string.
         *
         * @return  The IP hex address string.
         **************************************************************************************************/
        public string IpAddressHexString
        {
            get
            {
                if (IpAddress == null)
                    return "";
                var barry = new[]
                {
                    Convert.ToByte(IP1.Text),
                    Convert.ToByte(IP2.Text),
                    Convert.ToByte(IP3.Text),
                    Convert.ToByte(IP4.Text)
                };
                return AsciiHexConversionType.ByteArrayToHexWithSpaces(barry);
            }
        }
        /**************************************************************************************************
         * Gets the dotted IP address string.
         *
         * @return  The dotted IP address string.
         **************************************************************************************************/
        public string DottedIpAddressString
        {
            get
            {
                if (_ipAddress == null)
                    return "";
                return IpAddress.ToString();
            }
        }
        /**************************************************************************************************
         * Gets the ulong IP address.
         *
         * @return  The ulong IP address.
         **************************************************************************************************/
        public ulong UlongIpAddress
        {
            get
            {
                if (IpAddress == null)
                    return 0;
                var address = (ulong) (Convert.ToByte(IP1.Text) * (256 ^ 3)) +
                              (ulong) (Convert.ToByte(IP2.Text) * (256 ^ 2)) +
                              (ulong) (Convert.ToByte(IP3.Text) * 256) + Convert.ToByte(IP4.Text);
                return address;
            }
        }
        /**************************************************************************************************
         * Change focus.
         *
         * @param   ipTextBox   The IP control.
         **************************************************************************************************/
        private void ChangeFocus(TextBox ipTextBox)
        {
            switch (ipTextBox.Name)
            {
                case "IP1":
                    IP2.Select();
                    break;
                case "IP2":
                    IP3.Select();
                    break;
                case "IP3":
                    IP4.Select();
                    break;
                case "IP4":
                    ipTextBox.SelectNextControl(ActiveControl, true, true, true, true);
                    break;
            }
        }
        /**************************************************************************************************
         * Event handler. Called by IP1 for key press events.
         *
         * @param   sender  Source of the event.
         * @param   e       Key press event information.
         **************************************************************************************************/
        private void IP1_KeyPress(object sender, KeyPressEventArgs e)
        {
            var ipTextBox = sender as TextBox;
            switch (e.KeyChar)
            {
                case ''r':
                    SendKeys.Send("{TAB}");
                    e.Handled = true;
                    return;
                case ''t':
                    if (ipTextBox != null)
                        ChangeFocus(ipTextBox);
                    e.Handled = true;
                    break;
                default:
                    if (!char.IsDigit(e.KeyChar))
                        e.Handled = true;
                    break;
            }
        }
        /**************************************************************************************************
         * Event handler. Called by IP1 for text changed events.
         *
         * @param   sender  Source of the event.
         * @param   e       Event information.
         **************************************************************************************************/
        private void IP1_TextChanged(object sender, EventArgs e)
        {
            var ipTextBox = sender as TextBox;
            if (ipTextBox != null && ipTextBox.TextLength == 4)
            {
                ipTextBox.Text = ipTextBox.Text.Substring(0, 3);
                return;
            }
            if (ipTextBox != null && ipTextBox.TextLength == 3)
                ChangeFocus(ipTextBox);
        }
        /**************************************************************************************************
         * Event handler. Called by IP4 for key down events.
         *
         * @param   sender  Source of the event.
         * @param   e       Key event information.
         **************************************************************************************************/
        private void IP4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SendKeys.Send("{TAB}");
                e.Handled = true;
                e.SuppressKeyPress = true;
            }
        }
        /**************************************************************************************************
         * Event handler. Called by IpTextBoxes for change user interface cues events.
         *
         * @param   sender  Source of the event.
         * @param   e       User interface cues event information.
         **************************************************************************************************/
        private void IpTextBoxes_ChangeUiCues(object sender, UICuesEventArgs e)
        {
            _showFocusRect = e.ShowFocus;
        }
        /**************************************************************************************************
         * Raises the <see cref="E:System.Windows.Forms.Control.Enter" />
         *  event.
         *
         * @param   e   An <see cref="T:System.EventArgs" />
         *               that contains the event data.
         **************************************************************************************************/
        protected override void OnEnter(EventArgs e)
        {
            Invalidate();
        }
        /**************************************************************************************************
         * Raises the <see cref="E:System.Windows.Forms.Control.Leave" />
         *  event.
         *
         * @param   e   An <see cref="T:System.EventArgs" />
         *               that contains the event data.
         **************************************************************************************************/
        protected override void OnLeave(EventArgs e)
        {
            Invalidate();
        }
        /**************************************************************************************************
         * Raises the <see cref="E:System.Windows.Forms.Control.LostFocus" />
         *  event.
         *
         * @param   e   An <see cref="T:System.EventArgs" />
         *               that contains the event data.
         **************************************************************************************************/
        protected override void OnLostFocus(EventArgs e)
        {
            _hasFocus = false;
        }
        /**************************************************************************************************
         * Raises the <see cref="E:System.Windows.Forms.Control.Paint" />
         *  event.
         *
         * @param   e   A <see cref="T:System.Windows.Forms.PaintEventArgs" />
         *               that contains the event data.
         **************************************************************************************************/
        protected override void OnPaint(PaintEventArgs e)
        {
            var focusRect = ClientRectangle;
            focusRect.Inflate(-2, -2);
            if (_hasFocus && _showFocusRect)
                ControlPaint.DrawFocusRectangle(e.Graphics, focusRect, ForeColor, BackColor);
            else
                e.Graphics.DrawRectangle(new Pen(BackColor, 1), focusRect);
            base.OnPaint(e);
        }
        /**************************************************************************************************
         * Sets default IP address.
         *
         * @param   ip1 The first IP.
         * @param   ip2 The second IP.
         * @param   ip3 The third IP.
         * @param   ip4 The fourth IP.
         *
         * @return  The IPAddress.
         **************************************************************************************************/
        public IPAddress SetDefaultIpAddress(string ip1, string ip2, string ip3, string ip4)
        {
            IP1.Text = ip1;
            IP2.Text = ip2;
            IP3.Text = ip3;
            IP4.Text = ip4;
            return IpAddress;
            }
        }
}

这里是设计器代码

namespace Framework.UserApplication.CommonDialogs
{
    sealed partial class TcpIpInputMaskType
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Component Designer generated code
        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.pictureBox5 = new System.Windows.Forms.PictureBox();
            this.pictureBox4 = new System.Windows.Forms.PictureBox();
            this.pictureBox3 = new System.Windows.Forms.PictureBox();
            this.IP2 = new System.Windows.Forms.TextBox();
            this.IP3 = new System.Windows.Forms.TextBox();
            this.IP4 = new System.Windows.Forms.TextBox();
            this.IP1 = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox5
            // 
            this.pictureBox5.Image = global::Framework.Properties.Resources.dot1;
            this.pictureBox5.Location = new System.Drawing.Point(87, 26);
            this.pictureBox5.Name = "pictureBox5";
            this.pictureBox5.Size = new System.Drawing.Size(5, 5);
            this.pictureBox5.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox5.TabIndex = 91;
            this.pictureBox5.TabStop = false;
            // 
            // pictureBox4
            // 
            this.pictureBox4.Image = global::Framework.Properties.Resources.dot1;
            this.pictureBox4.Location = new System.Drawing.Point(57, 25);
            this.pictureBox4.Name = "pictureBox4";
            this.pictureBox4.Size = new System.Drawing.Size(5, 5);
            this.pictureBox4.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox4.TabIndex = 90;
            this.pictureBox4.TabStop = false;
            // 
            // pictureBox3
            // 
            this.pictureBox3.Image = global::Framework.Properties.Resources.dot1;
            this.pictureBox3.Location = new System.Drawing.Point(29, 25);
            this.pictureBox3.Name = "pictureBox3";
            this.pictureBox3.Size = new System.Drawing.Size(5, 5);
            this.pictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox3.TabIndex = 89;
            this.pictureBox3.TabStop = false;
            // 
            // IP2
            // 
            this.IP2.Location = new System.Drawing.Point(32, 5);
            this.IP2.Name = "IP2";
            this.IP2.Size = new System.Drawing.Size(27, 20);
            this.IP2.TabIndex = 86;
            this.IP2.TextChanged += new System.EventHandler(this.IP1_TextChanged);
            this.IP2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.IP1_KeyPress);
            // 
            // IP3
            // 
            this.IP3.Location = new System.Drawing.Point(61, 5);
            this.IP3.Name = "IP3";
            this.IP3.Size = new System.Drawing.Size(27, 20);
            this.IP3.TabIndex = 87;
            this.IP3.TextChanged += new System.EventHandler(this.IP1_TextChanged);
            this.IP3.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.IP1_KeyPress);
            // 
            // IP4
            // 
            this.IP4.Location = new System.Drawing.Point(90, 5);
            this.IP4.Name = "IP4";
            this.IP4.Size = new System.Drawing.Size(27, 20);
            this.IP4.TabIndex = 88;
            this.IP4.TextChanged += new System.EventHandler(this.IP1_TextChanged);
            this.IP4.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.IP1_KeyPress);
            // 
            // IP1
            // 
            this.IP1.Location = new System.Drawing.Point(3, 5);
            this.IP1.Name = "IP1";
            this.IP1.Size = new System.Drawing.Size(27, 20);
            this.IP1.TabIndex = 85;
            this.IP1.TextChanged += new System.EventHandler(this.IP1_TextChanged);
            this.IP1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.IP4_KeyDown);
            this.IP1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.IP1_KeyPress);
            // 
            // TcpIpInputMaskType
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.BackColor = System.Drawing.Color.Transparent;
            this.Controls.Add(this.pictureBox5);
            this.Controls.Add(this.pictureBox4);
            this.Controls.Add(this.pictureBox3);
            this.Controls.Add(this.IP2);
            this.Controls.Add(this.IP3);
            this.Controls.Add(this.IP4);
            this.Controls.Add(this.IP1);
            this.Name = "TcpIpInputMaskType";
            this.Size = new System.Drawing.Size(126, 31);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        #endregion
        private System.Windows.Forms.PictureBox pictureBox5;
        private System.Windows.Forms.PictureBox pictureBox4;
        private System.Windows.Forms.PictureBox pictureBox3;
        private System.Windows.Forms.TextBox IP2;
        private System.Windows.Forms.TextBox IP3;
        private System.Windows.Forms.TextBox IP4;
        private System.Windows.Forms.TextBox IP1;
    }
}

这是我项目中的"dot1",背景是透明的。当它后面有多个东西时,它会有点奇怪,但你可以在设计器中匹配颜色,没有问题。

如果我遇到什么问题,我会回来编辑这篇文章。

dot1.png

Windows WPF已经包含了这个功能。没有必要重新发明轮子。

进口需要:

System.Net.IPAddress
System.Windows.Forms.MaskedTextBox

现在,您需要设置属性:

MaskedTextBox.Mask = ###.###.###.### 
MaskedTextBox.ValidatingType = typeof(System.Net.IPAddress);