C# IP定制控件

#工具箱控件没有专用IP控件# #IP定制控件# 

一、定制IP的TextBox,命名为IPTextBox

(N年前的)

    /// <summary>
    /// IP_TextBox
    /// </summary>
    public class IPTextBox : TextBox
    {
        IPTextBox leftBox = null;
        IPTextBox rightBox = null;

        private string oldstr = string.Empty;

        public void setNeighbour(IPTextBox left, IPTextBox right)
        {
            leftBox = left;
            rightBox = right;
        }

        private static readonly string[] CharsNumber =
            {
                "NumPad0", "NumPad1", "NumPad2", "NumPad3", "NumPad4", "NumPad5", "NumPad6", "NumPad7", "NumPad8",
                "NumPad9","Left","Right","Back", "OemPeriod","Tab", "Delete", "Decimal",
                "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"
            };

        private bool _eventResult = false;
        private bool _eventResultImeProcessedKey = false;
        private bool _eventOnPreviewTextInput = true;

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            int resultNum = -1;
            bool resultBool = int.TryParse(Text, out resultNum);
            if (resultBool)
            {
                oldstr = Text;
            }
        }

        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (_eventOnPreviewTextInput)
            {
                int resultNum = -1;
                bool resultBool = int.TryParse(Text, out resultNum);
                if (resultBool)
                {
                    oldstr = Text;
                }
                
            }

            if (e.Key == Key.Back)
            {
                if ((CaretIndex == 0) && (leftBox != null) && SelectionLength == 0)
                {
                    leftBox.Focus();
                    leftBox.CaretIndex = leftBox.Text.Length;
                    e.Handled = true;
                }
            }
            if (e.ImeProcessedKey == Key.Back)
            {
                if ((CaretIndex == 0) && (leftBox != null) && SelectionLength == 0)
                {
                    leftBox.Focus();
                    leftBox.CaretIndex = leftBox.Text.Length;
                    e.Handled = true;
                }
            }

            if (e.Key == Key.Left)
            {
                if ((CaretIndex == 0) && (leftBox != null))
                {
                    leftBox.Focus();
                    leftBox.CaretIndex = leftBox.Text.Length;
                    e.Handled = true;
                }
            }
            if (e.ImeProcessedKey == Key.Left)
            {
                if ((CaretIndex == 0) && (leftBox != null))
                {
                    leftBox.Focus();
                    leftBox.CaretIndex = leftBox.Text.Length;
                    e.Handled = true;
                }
            }

            if (e.Key == Key.Right)
            {
                if ((CaretIndex == Text.Length) && (rightBox != null))
                {
                    rightBox.Focus();
                    rightBox.CaretIndex = 0;
                    e.Handled = true;
                }
            }
            if (e.ImeProcessedKey == Key.Right)
            {
                if ((CaretIndex == Text.Length) && (rightBox != null))
                {
                    rightBox.Focus();
                    rightBox.CaretIndex = 0;
                    e.Handled = true;
                }
            }

            string KeyTemp = e.Key.ToString();
            _eventResult = false;
            _eventResultImeProcessedKey = false;
            foreach (string charnum in CharsNumber)
            {
                if (charnum == KeyTemp)
                {
                    _eventResult = true;
                    break;
                }
            }
            string Key2Temp = e.ImeProcessedKey.ToString();
            foreach (string charnum in CharsNumber)
            {
                if (charnum == Key2Temp)
                {
                    _eventResultImeProcessedKey = true;
                    break;
                }
            }
            if (!((!_eventResult && _eventResultImeProcessedKey) || (_eventResult && !_eventResultImeProcessedKey)))
            {
                e.Handled = true;
            }
        }

        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            char ch;
            bool b;
            b = char.TryParse(e.Text, out ch);
            if (!b)
            {
                _eventOnPreviewTextInput = false;
                if (String.IsNullOrEmpty(oldstr))
                {
                    oldstr = "0";
                }
                return;
            }
            
            if (ch == '-' || ch == '。')
            {
                if (!String.IsNullOrEmpty(Text))
                {
                    if (Text.Length>1)
                    {
                        oldstr = Text.Remove(Text.LastIndexOf(ch));
                    }
                    else
                    {
                        oldstr = "";
                    }
                }
                _eventOnPreviewTextInput = false;
                return;
            }

            if (ch == '.')
            {
                if (!String.IsNullOrEmpty(Text))
                {
                    if (Text.Length > 1)
                    {
                        if (Text.Contains(".") || Text.Contains("。"))
                        {
                            oldstr = Text.Remove(Text.LastIndexOf(ch));
                            _eventOnPreviewTextInput = false;
                        }        
                    }
                    else
                    {
                    }
                }

                if ((rightBox != null)) // (CaretIndex == Text.Length) &&
                {
                    rightBox.Focus();
                    rightBox.SelectAll();
                    e.Handled = true;
                    return;
                }
            }

            int resultNum = -1;
            bool resultBool = int.TryParse(e.Text, out resultNum);
            if (resultBool)
            {
            }
            else
            {
                _eventOnPreviewTextInput = false;
                e.Handled = false;
                return;
            }

            if ((ch < '0' || ch > '9') /*|| !Char.IsDigit(ch)*/)
            {
                e.Handled = true;
                _eventOnPreviewTextInput = false;
                return;
            }
            else
            {
                _eventOnPreviewTextInput = true;
            }

            if ((Text.Length >= 3) && SelectionLength == 0)
            {
                //if (_eventResultImeProcessedKey)
                //{
                //    int pos = this.SelectionStart; // 输入法不同或Unicode编码
                //    if (Text == oldstr)
                //    {
                //        pos += 1;
                //    }
                //    Text = oldstr;
                //    if (pos >= 1)
                //    {
                //        this.SelectionStart = pos - 1;
                //    }
                //}
                if (_eventResult && !_eventResultImeProcessedKey)
                {
                    e.Handled = true;
                }
                
                return;
            }
        }

        protected override void OnTextInput(TextCompositionEventArgs e)
        {
            if (!_eventOnPreviewTextInput)
            {
                Text = oldstr;
            }

            int ipnumber = -1;
            bool resultBool = int.TryParse(e.Text, out ipnumber);
            if (resultBool && ipnumber > 255)
            {
                Text = "255";
                this.Select(Text.Length , 0);
            }
            int numTep = 0;
            var text = Text.Clone();
            if (e.TextComposition.AutoComplete == TextCompositionAutoComplete.On)
            {
                if (!String.IsNullOrEmpty(SelectedText))
                {
                    int g = Text.IndexOf(SelectedText, System.StringComparison.Ordinal);
                    text = Text.Remove(SelectionStart, SelectedText.Length);
                    text = text.ToString().Insert(g, e.Text);
                }
                else
                {
                    text = Text.Insert(SelectionStart, e.Text);
                }
            }
            resultBool = int.TryParse((String)text, out numTep);
            if (resultBool)
            {
                if (numTep > 255)
                {
                    e.Handled = true;
                }


                else
                {
                    base.OnTextInput(e);
                }
            }

            if (Text.Length == 3)
            {
                if ((CaretIndex == Text.Length) && (rightBox != null))
                {
                    rightBox.Focus();
                    rightBox.SelectAll();
                }
            }
        }

        protected override void OnLostFocus(System.Windows.RoutedEventArgs e)
        {
            base.OnLostFocus(e);

            if (Text == "")
            {
                Text = "0";
            }

            bool b = false;
            int ii = 0;
            try
            {
                b = int.TryParse(Text, out ii);
            }
            catch (Exception)
            {}

            if (!b)
            {
                Text = oldstr;
            }
        }
    }

二、IP定制控件

IPControl XAML文档

<UserControl x:Class="******.IPBox.IPControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
              xmlns:ipBox="clr-namespace:*****.IPBox"
             mc:Ignorable="d" 
             d:DesignHeight="30" d:DesignWidth="114.5" BorderThickness="1" BorderBrush="#FFC5C5C5">
    <Border BorderThickness="1" BorderBrush="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}">
            <StackPanel Orientation="Horizontal" Margin="0,0,0,0" Background="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}">
            <ipBox:IPTextBox x:Name="ipTextBox1" InputMethod.IsInputMethodEnabled="False" Height="25" Width="25" BorderThickness="0" HorizontalContentAlignment="Center" VerticalContentAlignment="Top" TextChanged="ipTextBox_TextChanged"/>
            <TextBlock Text="." Background="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" VerticalAlignment="Bottom"/>
            <ipBox:IPTextBox x:Name="ipTextBox2" InputMethod.IsInputMethodEnabled="False" Height="25" Width="25" BorderThickness="0" HorizontalContentAlignment="Center" VerticalContentAlignment="Top" TextChanged="ipTextBox_TextChanged"/>
            <TextBlock Text="." Background="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" VerticalAlignment="Bottom"/>
            <ipBox:IPTextBox x:Name="ipTextBox3" InputMethod.IsInputMethodEnabled="False" Height="25" Width="25" BorderThickness="0" HorizontalContentAlignment="Center" VerticalContentAlignment="Top" TextChanged="ipTextBox_TextChanged" />
            <TextBlock Text="." Background="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" VerticalAlignment="Bottom"/>
            <ipBox:IPTextBox x:Name="ipTextBox4" InputMethod.IsInputMethodEnabled="False" Height="25" Width="25" BorderThickness="0" HorizontalContentAlignment="Center" VerticalContentAlignment="Top" TextChanged="ipTextBox_TextChanged" />
            </StackPanel>
    </Border>
</UserControl>

IPControl cs文档

    /// <summary>
    /// IPControl.xaml 的交互逻辑
    /// </summary>
    public partial class IPControl : UserControl
    {
        public IPControl()
        {
            InitializeComponent();

            // 处理粘贴(好像没用)
            DataObject.AddPastingHandler(this, new DataObjectPastingEventHandler(IPTextBox_Paste));

            // 设置textBox次序
            ipTextBox1.setNeighbour(null, ipTextBox2);
            ipTextBox2.setNeighbour(ipTextBox1, ipTextBox3);
            ipTextBox3.setNeighbour(ipTextBox2, ipTextBox4);
            ipTextBox4.setNeighbour(ipTextBox3, null);
        }

        // 处理粘贴 类似ip的形式才能粘贴
        private void IPTextBox_Paste(object sender, DataObjectPastingEventArgs e)
        {

            if (e.DataObject.GetDataPresent(typeof(string)))
            {
                string value = e.DataObject.GetData(typeof(string)).ToString();
                setIP(value);
            }
            e.CancelCommand();
        }

        public string getIP()
        {
            return ipTextBox1.Text + "." + ipTextBox2.Text + "." + ipTextBox3.Text + "." + ipTextBox4.Text;
        }

        // 设置ip
        public bool setIP(string strIP)
        {
            string[] ips = strIP.Split('.');
            if (ips.Length == 4)
            {
                int res;
                for (int i = 0; i < ips.Length; ++i)
                    if (!Int32.TryParse(ips[i], out res) || res > 255 || res < 0)
                    {
                        return false;
                    }
                ipTextBox1.Text = ips[0];
                ipTextBox2.Text = ips[1];
                ipTextBox3.Text = ips[2];
                ipTextBox4.Text = ips[3];
                return true;
            }
            return false;
        }

        /// <summary>
        /// IP Text
        /// </summary>
        public string Text
        {
            get 
            {
                
                return (string)GetValue(TextProperty); 
            }
            set 
            { 
                SetValue(TextProperty, value);
            }
        }

        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(IPControl), new PropertyMetadata("", OnTextPropertyChanged));

        private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var ip = d as IPControl;
            if (!string.IsNullOrEmpty(ip.Text) && ip.Text.Contains("."))
            {
                ip.setIP(ip.Text);
            }
        }

        private void ipTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            Text = getIP();
        }
    }

三、试用

记得加上“InputMethod.IsInputMethodEnabled="False"”

<ipBox:IPControl x:Name="IP" Text="{Binding IP, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Row="0" Grid.Column="1" InputMethod.IsInputMethodEnabled="False" VerticalContentAlignment="Center" Margin="0,1,0,1"/>

若是不禁用输入

    public class NewTextBox : TextBox
    {
        private string oldstr = string.Empty;

        public static readonly DependencyProperty NumMaxNameProperty =
            DependencyProperty.Register("NumMax", typeof(int), typeof(NewTextBox), new PropertyMetadata(int.MaxValue));

        public static readonly DependencyProperty NumMinNameProperty =
            DependencyProperty.Register("NumMin", typeof(int), typeof(NewTextBox), new PropertyMetadata(0));

        public static readonly DependencyProperty NumDefautNameProperty =
            DependencyProperty.Register("NumDefaut", typeof(int), typeof(NewTextBox),
                                        new PropertyMetadata(default(int)));

        public int NumMax
        {
            get { return (int)GetValue(NumMaxNameProperty); }
            set { SetValue(NumMaxNameProperty, value); }
        }

        public int NumMin
        {
            get { return (int)GetValue(NumMinNameProperty); }
            set { SetValue(NumMinNameProperty, value); }
        }

        public int NumDefaut
        {
            get { return (int)GetValue(NumDefautNameProperty); }
            set { SetValue(NumDefautNameProperty, value); }
        }

        private static readonly string[] CharsNumber =
            {
                "NumPad0", "NumPad1", "NumPad2", "NumPad3", "NumPad4", "NumPad5", "NumPad6", "NumPad7", "NumPad8",
                "NumPad9","Left","Right","Back", "OemPeriod","Tab", "Delete", "Decimal",
                "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"
            };

        private bool _eventResult = false;
        private bool _eventResultImeProcessedKey = false;
        private bool _eventOnPreviewTextInput = true;

        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            Regex reg = new Regex("[^0-9.-]+");

            e.Handled = reg.IsMatch(e.Text);
        }

        protected override void OnTextInput(TextCompositionEventArgs e)
        {
            if (!_eventOnPreviewTextInput)
            {
                Text = oldstr;
            }

            var i = SelectionStart;
            int numTep = -1;
            bool resultBool = int.TryParse(e.Text, out numTep);
            if (resultBool && (numTep > NumMax/* || numTep < 0*/))
            {
                Text = NumMax.ToString();
                this.Select(Text.Length, 0);
            }
            var text = Text.Clone();
            if (e.TextComposition.AutoComplete == TextCompositionAutoComplete.On)
            {
                if (!String.IsNullOrEmpty(SelectedText))
                {
                    int g = Text.IndexOf(SelectedText, System.StringComparison.Ordinal);
                    text = Text.Remove(SelectionStart, SelectedText.Length);
                    text = text.ToString().Insert(g, e.Text);
                }
                else
                {
                    text = Text.Insert(SelectionStart, e.Text);
                }
            }
            resultBool = int.TryParse((String)text, out numTep);
            if (resultBool)
            {
                if (numTep > NumMax || numTep < 0)
                {
                    e.Handled = true;
                }
                else
                {
                    base.OnTextInput(e);
                }
            }
        }
        protected override void OnLostFocus(System.Windows.RoutedEventArgs e)
        {
            var text = Text.Clone();
            int numTep = NumMin;
            bool resultBool = int.TryParse((String)text, out numTep);
            if (resultBool)
            {
                if (numTep > NumMax || numTep < NumMin)
                {
                    Text = NumMin.ToString();
                }
            }

            if (Text == "")
            {
                Text = NumDefaut.ToString();
            }

            bool b = false;
            int i = 0;
            try
            {
                b = int.TryParse(Text, out i);
            }
            catch (Exception)
            {}

            if (!b)
            {
                Text = NumDefaut.ToString();
            }

            base.OnLostFocus(e);
        }
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值