C # Winform supports text boxes for Hex and ASCII input and switching

Source: Internet
Author: User

The following functions are implemented:

Hex, ASCII
Supports copy, paste, and cut operations. When you paste data, you can automatically check the format of the input data.
The Hex and ASCII input text boxes can be displayed.
When Hex is input, spaces are automatically added between every two characters.
I have passed some simple tests and have not found any bugs. If something is not well written or wrong, please leave a message to correct it.

 

 

 

Using System; using System. collections. generic; using System. text; using System. windows. forms; using System. componentModel; namespace LeafSoft. units {/// <summary> /// Hex/ASCII input text box // Author: yiye Zhiqiu // Date: July 11, 2013 /// you can enter Hex, ASCII /// you can switch between the Hex and ASCII input text boxes. // when Hex is input, spaces are automatically added between every two characters. // </summary> public class BytesBox: textBox {ContextMenuStrip CMenu = new ContextMenuStrip (); ToolStripMenuItem CM_Typ E = new ToolStripMenuItem (); ToolStripMenuItem CM_Clear = new ToolStripMenuItem (); public BytesBox () {# region shortcut menu 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 = "clear"; 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 attribute bool _ IsHex = true; [Description ("True: Hex; False: ASCII"), Category ("input format settings")] public bool IsHex {set {_ IsHex = value; if (_ IsHex) {CM_Type.Text =" SCII ";}else {CM_Type.Text =" Hex ";}}get {return _ IsHex ;}} # endregion # region menu operation // <summary> /// HEX/ASCII format switch /// </summary> /// <param name = "sender"> </ param> // <param name = "e"> </param> private void CM_Type_Click (object sender, eventArgs e) {if (IsHex) {// switch to the ASCII format IsHex = false; if (this. text. length> 0) {string [] HexStr = this. text. trim (). split (''); byte [] data = new byte [Hex Str. length]; for (int I = 0; I <HexStr. length; I ++) {data [I] = (byte) (Convert. toInt32 (HexStr [I], 16);} this. text = new ASCIIEncoding (). getString (data) ;}} else {// switch to the Hex format 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]);} t His. text = sb. toString ();}}} /// <summary> /// clear data /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private void CM_Clear_Click (object sender, eventArgs e) {this. text = "" ;}# endregion # region input control protected override void OnTextChanged (EventArgs e) {if (_ IsHex) {// Hex input string Content = this. text. replace ("", ""); // obtain the characters After spaces are removed. 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') // number 0-9 | (e. keyChar> = 'A' & e. keyChar <= 'F') // letter A-F | (e. K EyChar> = 'A' & e. keyChar <= 'F') // a-f | e. keyChar = 0x08 // return key | e. keyChar = 0x03 // copy | e. keyChar = 0x18) // cut {e. handled = false; return ;}} else {if (e. keyChar> = 0x20 & e. keyChar <= 0x7E) | e. keyChar = 0x08 // return key | e. keyChar = 0x0D // enter | e. keyChar = 0x03 // copy | e. keyChar = 0x18) // cut {e. handled = false; return ;}} if (e. keyChar = 0x16) // paste {// check the data format before pasting if (CheckPaste ()){ E. handled = false; return;} e. handled = true;} // <summary> // check the data format and /// </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') // digital 0-9 Key | (data> = 'A' & data <= 'F ') // letter A-F | (data> = 'A' & data <= 'F') // letter a-f | data = 0x20 )) // space {MessageBox. show ("pasted data contains illegal characters, can only contain numbers 0-9, uppercase letters A-F, lowercase letters a-f and space! "," Illegal pasting ", MessageBoxButtons. OK, MessageBoxIcon. Error); return false ;}} else {foreach (char data in PasteChar) {if (! (Data> = 0x20 & data <= 0x7E) | data = 0x0A | data = 0x0D) // enter the Enter key {MessageBox. show ("the pasted data contains invalid characters and can only contain ASCII characters! "," Illegal pasting ", MessageBoxButtons. OK, MessageBoxIcon. error); return false ;}}return true;} catch (Exception ex) {MessageBox. show (ex. message); return false ;}} # endregion # region public method // <summary> // obtain the command object // </summary> /// <returns> </returns> public Model. command GetCMD () {try {if (this. text. trim () = string. empty) {MessageBox. show ("the content is not allowed to be blank! "); 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> /// set the command object /// </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> /// Command object // </summary> public class Command {bool _ IsHex = true; byte [] _ DataBytes = null; /// <summary> /// do you want to perform hexadecimal data? // </summary> public bool IsHex {set {_ IsHex = value ;} get {return _ IsHex; }}/// <summary> // byte data // </summary> public byte [] DataBytes {set {_ DataBytes = value ;} get {return _ DataBytes ;}}} using System; using System. collections. generic; using System. text; namespace Model {// <summary> /// Command object // </summary> public class Command {bool _ IsHex = true; byte [] _ DataBytes = null; /// <summary> /// do you want to perform hexadecimal data? // </summary> public bool IsHex {set {_ IsHex = value ;} get {return _ IsHex; }}/// <summary> // byte data // </summary> public byte [] DataBytes {set {_ DataBytes = value ;} get {return _ DataBytes ;}}}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.