C# Winform 支援Hex與ASCII輸入和切換的文字框

Just4life發表於2014-08-12
using System;  
using System.Collections.Generic;  
using System.Text;  
using System.Windows.Forms;  
using System.ComponentModel;  
   
namespace LeafSoft.Units  
{  
    /// <summary>   
    /// Hex/ASCII輸入文字框   
    /// 作者:一葉知秋   
    /// 日期:2013年7月11日   
    /// 可輸入Hex,ASCII   
    /// 可切換顯示Hex與ASCII的輸入文字框   
    /// Hex輸入時可自動每2個字元之間新增空格   
    /// </summary>   
    public class BytesBox:TextBox  
    {  
        ContextMenuStrip CMenu = new ContextMenuStrip();  
        ToolStripMenuItem CM_Type = new ToolStripMenuItem();  
        ToolStripMenuItem CM_Clear = new ToolStripMenuItem();  
   
        public BytesBox()  
        {  
            #region 快捷選單   
            CM_Type.Name = "CM_Type";  
            CM_Type.Size = new System.Drawing.Size(127, 22);  
            CM_Type.Text = "ASCII";  
            CM_Type.Click += new System.EventHandler(CM_Type_Click);  
            CM_Clear.Name = "CM_Clear";  
            CM_Clear.Size = new System.Drawing.Size(127, 22);  
            CM_Clear.Text = "清空";  
            CM_Clear.Click += new System.EventHandler(CM_Clear_Click);  
            CMenu.Name = "CMenu";  
            CMenu.ShowImageMargin = false;  
            CMenu.Size = new System.Drawing.Size(128, 48);  
            CMenu.Items.AddRange(new ToolStripItem[] {  
            CM_Type,CM_Clear});  
   
            this.ContextMenuStrip = CMenu;  
            #endregion   
        }  
  
        #region 屬性   
        bool _IsHex = true;  
        [Description("True:Hex;False:ASCII"), Category("輸入格式設定")]  
        public bool IsHex  
        {  
            set {  
                _IsHex = value;  
                if (_IsHex)  
                {  
                    CM_Type.Text = "ASCII";  
                }  
                else 
                {  
                    CM_Type.Text = "Hex";  
                }  
            }  
            get {  
                return _IsHex;  
            }  
        }  
        #endregion  
  
        #region 選單操作   
        /// <summary>   
        /// HEX/ASCII 格式切換   
        /// </summary>   
        /// <param name="sender"></param>   
        /// <param name="e"></param>   
        private void CM_Type_Click(object sender, EventArgs e)  
        {  
            if (IsHex)  
            {//切換到ASCII格式   
                IsHex = false;  
                if (this.Text.Length > 0)  
                {  
                    string[] HexStr = this.Text.Trim().Split(' ');  
                    byte[] data = new byte[HexStr.Length];  
                    for (int i = 0; i < HexStr.Length; i++)  
                    {  
                        data[i] = (byte)(Convert.ToInt32(HexStr[i], 16));  
                    }  
                    this.Text = new ASCIIEncoding().GetString(data);  
                }  
            }  
            else 
            {//切換到Hex格式   
                IsHex = true;  
                   
                if (this.Text.Length > 0)  
                {  
                    byte[] data = new ASCIIEncoding().GetBytes(this.Text.Trim());  
                    StringBuilder sb = new StringBuilder();  
                    for (int i = 0; i < data.Length; i++)  
                    {  
                        sb.AppendFormat("{0:x2}", data[i]);  
                    }  
                    this.Text = sb.ToString();  
                }  
            }  
               
        }  
        /// <summary>   
        /// 清空資料   
        /// </summary>   
        /// <param name="sender"></param>   
        /// <param name="e"></param>   
        private void CM_Clear_Click(object sender, EventArgs e)  
        {  
            this.Text = "";  
        }  
        #endregion  
  
        #region 輸入控制   
        protected override void OnTextChanged(EventArgs e)  
        {  
            if (_IsHex)  
            {//Hex輸入   
                string Content = this.Text.Replace(" ", "");//獲取去除空格後的字元內容   
                int SpaceCount = Content.Length / 2;  
                int StartIndex = 2;  
                for (int i = 0; i < SpaceCount; i++)  
                {  
                    Content = Content.Insert(StartIndex, " ");  
                    StartIndex = StartIndex + 3;  
                }  
                this.Text = Content.TrimEnd().ToUpper();  
            }  
            this.SelectionStart = this.Text.Length;  
        }  
   
        protected override void OnKeyPress(KeyPressEventArgs e)  
        {  
            if (_IsHex)  
            {  
                if ((e.KeyChar >= '0' && e.KeyChar <= '9')//數字0-9鍵      
                     || (e.KeyChar >= 'A' && e.KeyChar <= 'F')//字母A-F    
                     || (e.KeyChar >= 'a' && e.KeyChar <= 'f')//字母a-f    
                     || e.KeyChar == 0x08//退格鍵   
                     || e.KeyChar == 0x03//拷貝   
                     || e.KeyChar == 0x18)//剪下   
                {  
                    e.Handled = false;  
                    return;  
                }  
            }  
            else 
            {  
                if ((e.KeyChar >= 0x20 && e.KeyChar <= 0x7E)  
                     || e.KeyChar == 0x08//退格鍵   
                     || e.KeyChar == 0x0D//Enter鍵   
                     || e.KeyChar == 0x03//拷貝   
                     || e.KeyChar == 0x18)//剪下   
                {  
                    e.Handled = false;  
                    return;  
                }  
            }  
            if (e.KeyChar == 0x16)//貼上   
            {//貼上前資料格式檢查   
                if (CheckPaste())  
                {  
                    e.Handled = false;  
                    return;  
                }  
            }  
            e.Handled = true;  
        }  
   
        /// <summary>   
        /// 貼上資料格式檢查   
        /// </summary>   
        /// <returns></returns>   
        private bool CheckPaste()  
        {  
            try 
            {  
                char[] PasteChar = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString().ToCharArray();  
                if (_IsHex)  
                {  
                    foreach (char data in PasteChar)  
                    {  
                        if (!((data >= '0' && data <= '9')//數字0-9鍵      
                         || (data >= 'A' && data <= 'F')//字母A-F    
                         || (data >= 'a' && data <= 'f')//字母a-f   
                         || data == 0x20))//空格   
                        {  
                            MessageBox.Show("貼上資料含有非法字元,只能包含數字0-9,大寫英文字母A-F,小寫英文字母a-f以及空格!", "非法的貼上", MessageBoxButtons.OK, MessageBoxIcon.Error);  
                            return false;  
                        }  
                    }  
                }  
                else 
                {  
                    foreach (char data in PasteChar)  
                    {  
                        if (!((data >= 0x20 && data <= 0x7E)  
                         || data == 0x0A  
                         || data == 0x0D))//Enter鍵   
                        {  
                            MessageBox.Show("貼上資料含有非法字元,只能包含ASCII碼字元!", "非法的貼上", MessageBoxButtons.OK, MessageBoxIcon.Error);  
                            return false;  
                        }  
                    }  
                }  
                return true;  
            }  
            catch (Exception ex)  
            {  
                MessageBox.Show(ex.Message);  
                return false;  
            }  
        }  
        #endregion  
  
        #region 公共方法   
        /// <summary>   
        /// 獲取命令物件   
        /// </summary>   
        /// <returns></returns>   
        public Model.Command GetCMD()  
        {  
            try 
            {  
                if (this.Text.Trim() == string.Empty)  
                {  
                    MessageBox.Show("不允許內容為空!");  
                    return null;  
                }  
                Model.Command Cmd = new Model.Command();  
                Cmd.IsHex = _IsHex;  
                if (Cmd.IsHex)  
                {//Hex   
                    string[] HexStr = this.Text.Trim().Split(' ');  
                    Cmd.DataBytes = new byte[HexStr.Length];  
                    for (int i = 0; i < HexStr.Length; i++)  
                    {  
                        Cmd.DataBytes[i] = (byte)(Convert.ToInt32(HexStr[i], 16));  
                    }  
                }  
                else 
                { //ASCII   
                    Cmd.DataBytes = new ASCIIEncoding().GetBytes(this.Text.Trim());  
                }  
                return Cmd;  
            }  
            catch(Exception ex)  
            {  
                MessageBox.Show(ex.Message);  
                return null;  
            }  
        }  
        /// <summary>   
        /// 設定命令物件   
        /// </summary>   
        /// <param name="Cmd"></param>   
        public void SetCMD(Model.Command Cmd)  
        {  
            try 
            {  
                this.IsHex = Cmd.IsHex;  
                if (this.IsHex)  
                {  
                    StringBuilder sb = new StringBuilder();  
                    for (int i = 0; i < Cmd.DataBytes.Length; i++)  
                    {  
                        sb.AppendFormat("{0:x2}", Cmd.DataBytes[i]);  
                    }  
                    this.Text = sb.ToString();  
                }  
                else 
                {  
                    this.Text = new ASCIIEncoding().GetString(Cmd.DataBytes);  
                }  
            }  
            catch (Exception ex)  
            {  
                MessageBox.Show(ex.Message);  
            }  
        }  
        #endregion   
    }  
}  



using System;  
using System.Collections.Generic;  
using System.Text;  
   
namespace Model  
{  
    /// <summary>   
    /// 命令物件   
    /// </summary>   
    public class Command  
    {  
        bool _IsHex = true;  
        byte[] _DataBytes = null;  
   
        /// <summary>   
        /// 是否16進位制資料   
        /// </summary>   
        public bool IsHex  
        {  
            set {  
                _IsHex = value;  
            }  
            get {  
                return _IsHex;  
            }  
        }  
   
        /// <summary>   
        /// byte資料   
        /// </summary>   
        public byte[] DataBytes  
        {  
            set 
            {  
                _DataBytes = value;  
            }  
            get 
            {  
                return _DataBytes;  
            }  
        }  
    }  
} 


相關文章