C # solution for inputting only numbers in textbox

Source: Internet
Author: User
Tags delete key

Source: collection and collation by China self-learning Programming Network
Release date:

 


Recently I have seen some blog posts about textbox that only allow numbers to be entered. This type of problem often uses post-event mode: to judge when the control leaves (such as the exit event) or when the input character ends. This article discusses the pre-processing mode of the control entry operation: the non-numeric characters are blocked during the input operation. Next, we will introduce a custom Textbox Control solution based on the modified tnumeditbox control, which is an open-source numeric text box.


In the custom Textbox Control, if only numbers are allowed, consider the following three situations:

1). Normal key input characters, including Spanish and Chinese characters
2). Press the keyboard shortcut key to paste the text, that is, CTRL + v.

3). Click "Mouse" in the context-related menu to paste the text, that is, "Paste ".

Most of the articles of the same type have considered only 1st cases and ignored 2nd and 3 common operations. The core idea of this article is to rewrite the event onkeypress () and two methods.
Processcmdkey () and wndproc (), and unify the CTRL + V and the paste operations of the associated menu into the keyboard input operation, so that
Onkeypress () Shields non-numeric keys.

1. Rewrite the keyboard event onkeypress ()
 

The characters entered by the keyboard can be processed by overwriting the onkeypress () event of the Textbox Control. See the following code:

Protected override void
Onkeypress (keypresseventargs e) // shield non-numeric keys

{

Base. onkeypress (E );

If (this. readonly) // read-only, not processed

Return;

If (INT) E. keychar <= 32 )//
Special key (including space), not processed

Return;

If (! Char. isdigit (E. keychar ))//
If it is not a numeric key, discard the input.

{

E. Handled = true;

Return;

}

}



2. Rewrite command key processing method processcmdkey ()
 

You can capture the shortcut key Ctrl + V in processcmdkey. First, you need to clear the selected text, read the content in the clipboard, and finally input the clipboard content by simulating keyboard input. It should be noted that the static method cannot be used in the processcmdkey () method.
Sendkeys. Send (), but you can use the wndproc () method of the control to send character messages to simulate keyboard input. See the following code:

Protected override bool processcmdkey (ref message MSG, keys keydata )//
Capture Ctrl + V

{

If (keydata = (KEYS) shortcut cut. ctrlv) // shortcut key Ctrl + V paste operation

{

This. clearselection ();

String text = clipboard. gettext ();

For (int K = 0; k <text. length; k ++) // can not
Use sendkeys. Send

{// Simulate keyboard input through the message. The sendkeys. Send () static method does not work.

Sendcharkey (Text [k]);

}

Return true;

}

Return base. processcmdkey (ref MSG, keydata );

}

 

Private void sendcharkey (char c) // input through the message simulation keyboard

{

Message MSG = new message ();

MSG. hwnd = This. Handle;

MSG. MSG = wm_char; // enter the keyboard character message

MSG. wparam = (intptr) C;

MSG. lparam = intptr. zero;

Base. wndproc (ref MSG );

}


3. Rewrite the Message Processing Method wndproc ()
 

You can create a context menu object with no content in the Custom Textbox Control to block the menu by adding the following code to the constructor of the custom control:
Public
Class customtextbox: textbox

{// Create a menu object without content, which is equivalent to shielding the context menu of the control

This. contextmenu = new contextmenu ();

}

Since the paste operation in the context menu corresponds to the wm_paste message in Windows, you can capture the message in the wndproc () method of the control and then obtain the clipboard.
The content in the clipboard is finally simulated by using the sendkeys. Send () method. Note that the preceding processcmdkey () cannot be called here ()
Simulate the keyboard input function sendcharkey (). See the following code:
Protected override void wndproc (ref
Message m) // capture mouse paste messages

{

If (M. MSG = wm_paste) // select the "Paste" Operation in the context menu

{

This. clearselection ();

Sendkeys. Send (clipboard. gettext (); // simulate keyboard input

}

Else

{

Base. wndproc (ref m );

}

}


4. Clear clearselection () and delete the etext () character ()


You must also analyze the two functions in the previous Code:

Clearselection () is used to clear the current selected text, that is, clear this. selectedtext

Deletetext () deletes the current character

The trick is to convert the delete key operation to the backspace operation. In addition, the deletetext () function also needs to determine the current this. selectionstart value. The Code is as follows:

Private void clearselection () // clear the selection of the current textbox

{

If (this. selectionlength = 0)

Return;

Int sellength = This. selectedtext. length;

This. selectionstart + = This. selectedtext. length; // After the cursor is selected

This. selectionlength = 0;

For (int K = 1; k <= sellength; k ++)

This. deletetext (Keys. Back );

}

 

Private void deletetext (Keys key) // Delete the character and calculate the selectionstart Value

{

Int selstart = This. selectionstart;

If (Key = keys. delete) // convert the delete operation to the backspace operation.

{

Selstart + = 1;

If (selstart> base. Text. length)

Return;

}

If (selstart = 0 | selstart> base. Text. Length )//
No need to delete

Return;

If (selstart = 1 & base. Text. Length = 1)

{

Base. Text = "";

Base. selectionstart = 0;

}

Else // selstart> 0

{

Base. Text = base. Text. substring (0, selstart-1) +
Base. Text. substring (selstart, base. Text. Length-selstart );

Base. selectionstart = selstart-1;

}

}


5. Conclusion


This article describes the pre-processing mode of Textbox Control Input, that is, shielding non-numeric keys while inputting characters. In practical applications, the post-processing mode is generally adopted, that is,
Input post-processing in events such as exit and validate -- verification is performed when the control is left. However, the post-event processing mode has the following shortcomings:

When binding to a data source, inputting non-numeric characters may throw an exception. You need to consider exception capture.
Data needs to be judged and error prompts must be provided.


The above content is removed from the author's open-source numeric data editing control tnumeditbox. This control takes into account much more complex situations than allowing only digital input. Interested parties can refer to and correct it. It should be noted that the core idea of tnumeditbox comes from the free Delphi control pbnumedit and open-source C # control banumedit. In return, I will also
Tnumeditbox is open-source and released to codeproject.

Here we will discuss the shielding of non-numeric key input, which can obviously be extended to blocking other special keys, such as tabs and specified letters.

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.