Develop a Windows ApplicationProgramThe input verification of the control is indispensable, and there are countless input verification methods added. Here we will introduce a method for adding input verification to your Textbox Control Using the sophus Interception Function. "Very clean" indicates that input verification can be added and deleted transparently without considering any user logic.Code.
Now we have a textbox named textbox1 and a button named button1.
This button1 has a click event. The Code is as follows:
Private Void Button#click ( Object Sender, system. eventargs E)
{
MessageBox. Show ("The number is \""+ Textbox1.text +"\"");
}
What if we want to add an input verification to the textbox1 control without modifying the code of button1?
Let's take a look at the textbox1.text attribute. This attribute is a virtual attribute, which means it can be intercepted, the following code uses the iinterceptor interface provided by sophus to implement an interceptor interface:
Public Class Numbervalidationinterceptor: iinterceptor
{
Public Object Intercept (iinvocation invocation, Params Object [] ARGs)
{
String Retstring = Invocation. Proceed (ARGs) As String ;
If (RegEx. ismatch (retstring, @" ^ [+-]? \ D * [.]? \ D * $ " ))
{
ReturnRetstring;
}
Else
{
MessageBox. Show ( " Please input a number. " , " Validation failure " , Messageboxbuttons. OK, messageboxicon. Warning );
Return " 0 " ;
}
}
}
what is the blocker to intercept? Next we define a contract, which contains detailed information such as the object and method to intercept. The Code is as follows: emitproxycontract contract = New emitproxycontract ();
contract. target ( typeof (textbox ));
contract. intercept ( typeof (numbervalidationinterceptor ), " get_text " );
the next step is to create the dynamic proxy type emitproxy proxy = ( New emitproxyfactory ()). getproxy (contract);
proxy. independent = true ;
Here we use independent = true, which means that the dynamic proxy configuration can be independent from other dynamic proxy configurations that use the same contract, so that some advanced features of sophus can be used, as shown belowTextbox1=Proxy. Wrap (This. Textbox1)AsTextbox;
This sentence uses the textbox1 Type Packaged by sophus to dynamically replace the original textbox1, And the textbox1 instance has not changed. You can see the controls on the form to know, however, the above button1 will be dynamically hooked during click, which is the magic of sophus.
When textbox1 does not input a number, the dynamic interceptor takes effect.
Download the free version of sophus: http://research.grapecity.com.cn/cs/files/7/sophus/default.aspx from here
Sophus Forum: http://research.grapecity.com.cn/cs/forums/14/ShowForum.aspx