Using C # to make a text box for imitation IE address column

xiaoxiao2021-03-06  43

Using C # to make a text box for imitation IE address column

When using the IE Internet, simply enter several letters in the address bar, the address of these letters blur will automatically display the user selection, the user is traversed in the existing options by pressing the keyboard, the user is traversed in the existing option. After finding the option you need, press Enter to choose, or use the mouse to operate directly, it is very convenient, we can also use this feature in the program to implement the automatic prompt, so that the user input, the following will take an example Introduction, how I am implemented in work.

As can be seen from the above figure, the best way seems to inherit the ComboBox write a control. In the TextChanged event, according to the content change, decide whether to pull the prompt box, and what the prompt is, in practice, we found that Combobox It is very difficult to control. If you modify the SelectedIndex property, the TextChanged event will be automatically generated, causing dead loops, etc., although other variables can be added to mark that the text change is caused by the user or by the procedure, but The effect is always unsatisfactory, after repeated test, finally selects the way the text box list box is selected, and the control library is used for other programs, the effect is ideal, where the text box receives the user input, the list box provides options to choose.

Create a normal Windows application to test, you may wish to name Test, then click Menu File "→" Add Project "→" New Project (N) ", select" Windows Control Library "from the pop-up dialog box ", Put the project and test items in the same folder, you may wish to name" TextBoxext ", which is the focus of this article.

In "Solution Explorer", right-click the "TextBoxext" project, select "Properties" from the pop-up menu, pop-up the property configuration dialog box, select all configurations in "Configuration (C)" in the upper left corner ", Set the output path to" ../output ", note that this input is a bit special, two decimal points backslash Output, meaning the current folder on the Ouput folder (may compare from VC) Familiar with this way)

Compile, we can see it in "My Computer" or "Resource Manager".

TextBoxext

The file folder automatically creates one level

OUTPUT

Folder, output

TextBoxext.dll

Lying here

Continue to configure the dependency, point menu "Item" → "Set dependence (D)", set the project test depending on "TextBoxext", to this, the development environment is complete.

Double-click the "UserControl1.cs" file in the Solution Explorer, and then switch to the code window. For easy reference, we change the namespace "Namespace TextBoxext" to "Namespace Tools", because this control is inherited in the text box, so

Public Class UserControl1: System.Windows.Forms.userControl

{

Public userControl1 ()

{

InitializationComponent ();

}

change into:

Public class textboxext: system.windows.Forms.TextBox

{

Private system.componentmodel.Container Components = NULL; public textBoxext ()

{

}

That is to say, change the namespace to Tools, change the class name to TextBoxext, let this class inherit the class inheritance in System.Windows.Forms.TextBox and modify the corresponding constructor. After the compilation is successful, double-click the "form1.cs" of the project "Test" to switch to the form design, switch to the "My User Control" option in the Toolbox window, in Click the "Add / Transfer" from the pop-up menu, then pop up a dialog, click the "Browse" button to find the last point "OK" button that is currently generated, in "Toolbox "A" TEXTBOXEXT "control in" My Control Library ", which is the same as the normal text box control, add several custom controls on the form. It can be seen that the text box used by the text box is exactly the same.

Switch to the UserControl1.cs Code Design window, add a list box variable to display the prompt:

Private system.windows.forms.listbox m_lstshowchoice = NULL;

Add a piece of code to respond to the MouseUp event of the list box mouse, that is, the user selects by clicking on the list box:

Private void Lstbox_mouseup (Object Sender, System.Windows.MouseEventArgs E)

{

Listbox box = (listbox) Sender;

IF ((Box.SelectedIndex> -1) &&! this.readonly)

{

THIS.TEXT = Box.SelectedItem.tostring ();

// Select the text box lost the focus, here moved back

THIS.FOCUS ();

}

}

Add the mouse to move the event in the list box, when the user moves the mouse in the list box, automatically sets the list box current item according to the mouse position.

Private void Lstbox_mousemove (Object Sender, System.Windows E)

{

Listbox box = (listbox) Sender;

Point Pt = New Point (E.x, E.Y);

INT N = Box.indexFromPoint (PT);

IF (n> = 0)

Box.selectedIndex = N;

}

For the sake of beauty, you can set the foreground, background, border style, etc. of the list box, according to regular, we can set up a public variable for program call, but cannot be directly modified by the property window when the program is designed, inconvenient, through "nature" The reference can be solved, the following code is the background of the set list box, which is better understood:

#Region Settings the background of the prompt box

Private color m_lstforcolor = system.drawing.systemcolors.infotext;

///

/// Set / get the background color of the prompt

///

Public Color PromptbackColor

{

get

{

Return M_LstbackColor;

}

set

{

M_LstbackColor = Value;

// Lstprompt creation See the code below

Listbox box = this.lstprompt; if (box! = Null)

Box.backcolor = m_lstbackcolor;

}

}

#ndregion

Set the foreground, the method of the border is exactly the same, no longer described, after thus processing, we can specify directly in the "Properties" window during programming.

Next, it is also "nature" to return to the current list box, if not yet created:

Private system.windows.forms.listbox Lstprompt

{

get

{

// If there is no list to display the list box of the prompt, create one

IF (m_lstshowchoice == null) && this.parent! = null)

{

M_LstshowChoice = new listbox ();

m_lstshowchoice.visible = false;

m_lstshowchoice.Lesteft = this.Left;

m_lstshowchoice.top = this.bottom;

m_lstshowchoice.width = this.width;

M_Lstshowchoice.TABSTOP = FALSE;

m_lstshowchoice.sorted = true;

m_lstshowchoice.forecolor = this.m_lstforcolor; // Prospect

m_lstshowchoice.backcolor = this.m_lstbackcolor; // Background (see M_LstForcolor creation

m_lstshowchoice.borderstyle = this.m_lstbordrsty; // Border, Background (see M_Lstforcolor creation

// If the prompt is too low, it is displayed above.

IF (M_Lstshowchoice.BOTTOM> this.parent.height)

m_lstshowchoice.top = this.top-m_lstshowchoice.height 8;

M_Lstshowchoice.MouseUp = new system.windows.forms.mouseeventhandler (this.lstbox_mouseup);

M_Lstshowchoice.Mousemove = new system.windows.forms.mouseeventhandler (this.lstbox_mousemove);

This.Parent.controls.add (m_lstshowchoice);

This.Parent.ResumeLayout (FALSE);

M_Lstshowchoice.BRINGTOFRONT ();

}

Return M_LstshowChoice;

}

}

Create an ArrayList to store all available items:

Private arraylist m_forchoice = new arraylist ();

Public ArrayList ChoiceArray

{

get

{

Return m_forchoice;

}

set

{

m_forchoice = (arraylist) (Value.clone ());

Listbox box = this.lstprompt;

IF (box! = null)

{

Box.Items.clear ();

Box.items.addrange (m_forchoice.toArray ());

}

}

}

When the user is input, often like to add spaces, such as the name "Zhang San", users like to be "Zhang San", although it can be aligned with the names of the three words, but the name retrieval of the program, etc. Very inconvenient, because you still have to judge whether there is space in the middle, how many spaces, etc., for this, we set a "nature" to determine whether the user is allowed to enter space. PRIVATE BOOL M_AllowSpace = FALSE;

Public Bool AllowSpace

{

get

{

RETURN M_AllowSpace;

}

set

{

M_AllowSpace = Value;

}

}

In the input process, some content can only be selected, just like we set the ComboBox's DropDownStyle to DropDownList, but for the convenience of users, we allow users to enter, when the cursor leaves this text box, check, determine the user input Whether the content is in an option, if not, clear the user input, so add the following variables:

PRIVATE BOOL M_BCHOICEONLY = FALSE;

Public Bool Choiconly

{

get

{

Return this.m_bchoiceonly;

}

set

{

THIS.M_BCHOICEONLY = VALUE;

}

}

According to the common sense, we should decide whether to display the list box according to the text change in the TextChange event in the response text box, and which options should appear in the list box, but as ComboBox, text change events may have a variety of events (such as The program uses textBox1.text = "abc"), it is difficult to control, we respond to the keyup event here, and the above problems are avoided through keyup and keydown. In this article, we can say that "↑" and "↓" on the keyboard can be traversed in the options, and the text box is used to move the current keyboard cursor, so we write down the current cursor location in KeyDown. In Keyup, declare a variable m_noldpos to record the keyboard cursor position in front of the button. In actual work we found that some input methods have bugs. After the user typing a key, a keydown generates two Keyup events, for Therefore, by a variable bKeyDown records whether the key is pressed, the text change occurs between KeyDown and Keyup, so the current text must be recorded in keydown, and the text is determined whether the text changes, according to the above analysis, We add the keydown event response code of the text box:

Private int m_noldpos = 0;

PRIVATE BKEYDOWN = FALSE;

Private string m_stroldtext = "";

Private void textboxext_keydown (Object Sender, System.Windows), Keyeventargs E)

{

m_noldpos = this.selectionstart;

BKEYDOWN = True;

m_stroldtext = this.Text;

}

Create a function to use the text box current content, filter out a fuzzy matching option from the available M_Forchoice array, add it to the list box: Private void newprompt (string p_strtext)

{

Listbox box = this.lstprompt;

IF (box! = null)

{

Box.Items.clear ();

IF (p_strtext.length == 0) // No content, display all

Box.items.addrange (this.m_forchoice.toArray ());

Else

{

Foreach (String s in this.m_forchoice)

{

IF (s.tolower (). Indexof (p_strtext.tolower ())> = 0)

Box.Items.Add (s);

}

}

}

}

Add the keyup event response code of the text box:

Private void textboxext_keyup (Object Sender, System.Windows E)

{

IF (! bkeydown) / / ignore extra KEYUP events

Return;

BKEYDOWN = FALSE;

Listbox box = this.lstprompt;

Switch (E.Keycode)

{

// Move in the standby box through the up and down arrow

Case system.windows.forms.keys.up:

Case system.windows.forms.keys.down:

IF ((box! = null) &&! this.multiline) // Multi-line text moves between the two lines through the up and down arrows

{

IF ((e.keycode == system.windows.forms.keys.up) && (box.selectedindex> -1)) // ↑

Box.selectedIndex -;

Else IF ((e.keycode == system.windows.forms.keys.down) && (Box.selectedIndIndex

Box.selectedIndex ;

// The up and down arrow cannot move the current cursor, so restore the original position

This.SelectionStart = m_noldpos;

// Display prompt box

IF (! box.visible)

{

IF (Box.Width! = this.width)

Box.width = this.width;

Box.visible = true;

}

}

Break;

Case system.windows.Forms.keys.escape: // esc hidden tips

IF ((Box! = null) && box.visible)

Box.hide ();

Break;

Case system.windows.Forms.keys.Return: // Enter one or jump to the next control

IF ((Box == Null) || this.multiline)

Break;

/ / Move to the next control when no prompt box

IF (! box.visible)

{

SendKeys.send ("{tab}");

}

Else // has a prompt, close prompt

{

IF (Box.SelectedIndex> -1) // Select, use the current selection

THIS.TEXT = Box.SelectedItem.tostring ();

THIS.SELECTIONSTART = this.text.length; this.selectall ();

Box.hide ();

}

Break;

DEFAULT: / / Decades if the text changes

String strText = this.text;

// Do not allow a space to get a space in the text

IF (! m_allowspace)

Strtext = this.Text.Replace ("," ");

INT NSTART = this.selectionStart;

IF (strText! = m_stroldtext) // text has changed

{

/ / Set the current text and keyboard cursor position

THIS.TEXT = STRText;

IF (nStart> this.text.length)

NStart = this.Text.Length;

This.SelectionStart = NStart;

/ / Modify the available content and display the list of supplied to the selection

IF (box! = null)

{

This.FillPrompt (strText);

IF (! box.visible)

{

IF (Box.Width! = this.width)

Box.width = this.width;

Box.visible = true;

}

}

}

Break;

}

}

When the text box loses the keyboard cursor, you must hide the prompt. For the only type text box, it is necessary to judge whether the user input is in the option:

Private Void TextBoxext_leave (Object Sender, System.EventArgs E)

{

// For the only field, you must enter the value of matching match.

IF (this.m_bchoiceonly)

{

INT NINDEX = this.choiceArray.indexof (this.text);

IF (NINDEX <0)

THIS.TEXT = ""

}

// After you lose the focus, you must hide the prompt.

Listbox box = this.lstprompt;

IF (box! = null)

Box.visible = false;

}

In the IE address bar, there is a "↓" on the right, we can click this arrow to open the prompt box, this example does not increase this feature can not be a defect, here, we have double-click the text box (also You can simulate the drop-down arrow by adding a button on the right, and the method of making a manual article "Make a combination control in C #"):

Private void textboxext_doubleclick (Object Sender, System.Eventargs E)

{

IF (this.readonly)

Return;

Listbox box = this.lstprompt;

IF ((Box! = null) && (! box.visible))

{

IF (Box.Width! = this.width)

Box.width = this.width;

Box.visible = true;

}

}

Switch to the Test Project Form1 code window, add a reference to the previous: Using Tools; and add Form1 LOAD event response code:

Private Void Form1_Load (Object Sender, System.EventArgs E)

{

// Create an array to populate the options for this control

ArrayList arr = new arraylist ();

Arr.Add ("Aaabbbcccddd");

Arr.add ("bbbcccddeeee"); arr.add ("cccdddeeefff");

Arr.Add ("DDDeeeffFGGG");

// Traverse all controls, filter out the enhanced text box control to assign an option assignment

Foreach (Control CTL in this.Controls)

{

TextBoxExt txtbox = CTL as textboxext;

IF (txtbox == null)

CONTINUE;

TXTBOX.CHOICEARRAY = Arr;

}

}

Run, when you enter some letters in the text box, the text box will automatically match, remove the text that does not meet the requirements, and by pressing the up and down arrow, the Enter key, ESC key, double-click, etc. can be checked.

At this point, similar

IE

The controls of the address bar have been completed, and the control can be expanded in the work. If you add a "representative field" in the control, you specify the field represented in the properties window when you design the program design, and "Name"). Above

Form1

of

Load

Incident

Foreach

Control CTL in this.Controls)

"In this field, according to this field, all names are automatically searched from the database, and fill it into the options for the text box for the user to choose, this is not necessary, there is no need to be in the code to specify a text box with what field is bound, big Decompose the work, even the text box

Name

Attributes can not be specified, and strong versatility, the above is just a thinking and backbone code, and the actual control is much stronger, you can constantly improve and supplement according to our own work

转载请注明原文地址:https://www.9cbs.com/read-59480.html

New Post(0)