C # key processing techniques

xiaoxiao2021-03-06  70

The Keys ON A Computer Keyboard, Unlike Those In A Convenctional Typewriter, Fall Into Several Categories:

Normal INPHANUMERIC Characters and Punctuation Marks. Function Keys: F1 To F12. Control Keys: Control, Alt, Shift, The Arrow Keys, And Others.

Processing the complete set of keys not only requires the detection of the pressing of individual key, but also the pressing of keys in combination. For this article, I have written two versions of a user control called WhiteBoard. The first version, given in Listing 1, captures keys in the first category; however, it can not capture function and control keys The second version, given in Listing 3, captures all keys.Both versions are covered in the sections "Processing Characters" and. "Processing All Keys." note that in my testing with the current version of the .NET Framework SDK (version 1.0), the KeyDown event in System.Windows.Forms.Control is not triggered when the user presses an arrow key. However, the KeyDown event in System. Windows.Forms.Form is raised when an arrow key is pressed. The Form class extends the ContainerControl class, which extends the ScrollableControl class. The ScrollableControl class is a direct child class of the Control class. The class library reference in the .NET Framework SDK documentation does not state that the KeyDown event or the OnKeyDown method are overriden in any of ContainerControl, ScrollableControl, or Form. Therefore, the behavior of this event in both the Form and the Control classes must be the same. This Leads to the Following Possibilities: Either the documentation is not up to date or there is a bug in the class library.processing character

If the user presses a key on the keyboard when a control has focus, three events of the control are triggered The three key events occur in the following order:.. KeyDown Occurs when the user starts pressing the key, ie, when the key is Down. Keypress. Occurs WHEN A KEY IS PRESSED, AFTER THE Keydown Event IS Triggered. Keyup. Occurs When The User Releases The key.

The easiest way to capture keyboard input from the user is to use the KeyPress event of a control The event handler for this event receives a System.Windows.Forms.KeyPressEventArgs object containing two properties.:

Handled. A Boolean Indicating WHETHER THE HAS BEEN HAND. KEYCHAR. A Read-Only Property from Which The Corresponding Character of The Pressed Key Can Be Obtained.

Since the KeyChar property gives you the character of the key being pressed, displaying the character, for example, is very straightforward. However, some keys do not have visual representation and are not meant to be displayed. The backspace key, for instance, is normally used in a text-based control to delete the character to the left of the caret and move the caret back one character. in this case, you can simply convert the character into an integer and compare the integer with the ASCII value of the character C = E.KeyChar; INT i = (int) C;

The Backspace Key Will Have An Integer Value of 8 and The Carriage-Return Key 13. The Use of the Keypress Event Is Illustrate In The Whiteboard Control Displayed IN A Form in Figure 1.

Figure 1. The Whiteboard Control That Captures Characters.

The Whiteboard Control Extends The System.Windows.Forms.userControl Class and ITS Code Is Given in Listing 1.

As can be seen in Figure 1, the WhiteBoard control is a two-dimensional array of characters that has a visual interface The two-dimensional array is represented by the variable board private char [,] board;.. The dimensions are indicated by the Variables columncount and rowcount.

Board = new char [columncount, rowcount];

Every time the OnPaint method of the control is invoked, the value of each element of the array is drawn using the DrawString method of the Graphics object of the control. The location of each character is determined by characterWidth, characterHeight, and lineSpace. The latter INDICATES The Distance Between Two Lines in Pixels.

Protected Override Void Onpaint (Painteventargs E)

{

Graphics graphics = E.Graphics;

Font Font = New Font ("Courier New", CharacterWidth;

Brush brush = new solidbrush (forecolor);

For (INT i = 0; i

{

For (int J = 0; j

{

Graphics.drawstring (Board [i, j] .tostring (), font, brush,

New Point (i * CharacterWidth, J * (Linespace CharacterHeight)))))));

}

}

.

.

.

Like most decent text-based controls, our WhiteBoard control uses a caret to tell the user the location of the current character insertion point. That's right, a caret does not come free. You have to draw your own caret and make it blink (animate .) in our WhiteBoard control, the location of the caret is determined by two integers: caretX and caretY They indicate the horizontal and vertical coordinates in the visual area Every time the user presses a key, the caret is moved forward by one character.. ................

The animation of the caret is achieved by the use of the System.Threading.Thread class. Surprisingly, thanks to the classes in the System.Threading namespace, multi-threaded programming is relatively easy. The Thread class represents a thread in the program. in the WhiteBoard control, we use a thread called caretThread for displaying and animating the caret in the right position: private Thread caretThread ;. When the control is created, caretThread must already be ready Therefore, we start the caret thread in the class's constructor. .caretthread = new thread (New ThreadStart (Showcaret);

Caretthread.start ();

In The Above Code, The First Line Constructions A

Thread Object and Informs The Thread That It Is To Handle Thala

SHOWCARET METHOD. The Second Line Starts The Thread, I.E., Starts Executing The

Showcaret Method. Before We Look At The

ShowCaret method, however, bear in mind that you are responsible for stopping and destroying the thread when it is no longer needed. Failure to do so will make the program unable to exit properly. In our WhiteBoard control, this is handled by overriding the control's

Dispose method.

Protected Override Void Dispose (Bool Disposing)

{

IF (disposing) {

Caretthread.abort ();

}

Base.dispose (Disposing);

}

Therefore, when the control is disposed, the Thread class's Abort method will be called to terminate the thread. The ShowCaret method, as seen in Listing 1, employs an indefinite while loop that makes the thread execute the same piece of code. The code in this while loop is simple. It invalidates the part of the Graphics object that is occupied by the caret. The Update method is then called. This will invoke the OnPaint method, but the control will only redraw the area indicated by the rectangle passed to the Invalidate method. Whether or not the caret is visible is determined by the caretVisible variable. If it is true, the vertical line is drawn. Otherwise, nothing is drawn, making the caret invisible. The rate at which the caret blinks is determined by the Value Passed to the Sleep Method of the Thread Class. Here We Use 350. The Caretvisible Variable IS Also Toggled To Create The Blinking Effect.This.invalidate (NEW

Rectangle (Caretx * CharacterWidth, Carety * (CharacterHeight Linespace),

Caretx * CharacterWidth 2 * Penwidth, (Carety 1) * (CharacterHeight

LINESPACE))))

This.Update ();

Thread.sleep (350);

CaretVisible =! CaretVisible;

The Caret Itself Is Drawn When The onpaint method is Called:

// Draw Caret Here;

IF (CaretVisible)

{

INT x = caretx * characterwidth;

INT Y = CARETY * (Linespace CharacterHeight);

Graphics.drawline (Pen, X, Y, X, Y Linespace CharacterHeight);

}

Now, let's discuss the KeyPressed method that is called every time a key is pressed. First, the KeyPressed method must be registered to become the handler of the KeyPress event. We do it in the class's constructor.

this.KeyPress = new KeyPressEventHandler (KeyPressed); The handling of keys is not that complex Basically, our simple WhiteBoard control accepts all alphanumeric characters and punctuation marks The method also detects the keying of backspace (ASCII 8) and makes backspace function.. Properly.

CHAR C = E.KeyChar;

INT i = (int) C;

IF (i == 8)

{

IF (Caretx == 0)

{

Caretx = columncount - 1;

Carety -;

IF (Carety <0)

Carety = rowcount - 1;

}

Else

{

Caretx -

}

Board [Caretx, Carety] = '';

For Non-Backspace Characters, The Method Moves The Caret Forward by One Character.

Board [Caretx, Carety] = C;

Caretx ;

IF (Caretx == Columncount)

{

Caretx = 0;

Carety ;

IF (Carety == RowCount)

Carety = 0;

}

}

IT THEN INVALIDATES The Control So That The Graphics Object Is Repainted. Calling The invalidate Method WITHOUT AN Argument Will Repaint The Whole Area of ​​The Graphics Object.

THIS.INVALIDATE ();

This.Update ();

The Code in Listing 2 Is A Form That Uses The Whiteboard Control.LISTING 2. A Form That Uses The Whiteboard Control

Using system;

Using system.componentmodel;

Using system.windows.forms;

Using system.drawing;

Namespace KeyProcessor

{

Public Class Form1: System.Windows.Forms.form

{

Private keyprocessor.Whiteboard Whiteboard;

Private system.componentmodel.Container Components = NULL;

Public Form1 ()

{

InitializationComponent ();

}

Protected Override Void Dispose (Bool Disposing)

{

IF (Disposing)

{

IF (Components! = NULL)

{

Components.dispose ();

}

}

Base.dispose (Disposing);

}

#Region Windows Form Designer Generated Code

Private vidinitiRizeComponent ()

{

Whiteboard = new whiteboard (); this.suspendlayout ();

Whiteboard.location = new point (20, 20);

Whiteboard.size = new size (190, 220);

THIS.AUTOSCALEBASESIZE = New System.drawing.size (5, 13);

THIS.CLIENTSIZE = New System.drawing.size (292, 273);

This.Controls.addRange (new system.windows.forms.control [] {whiteboard};

THIS.NAME = "Form1";

This.Text = "Small Whiteboard";

This.ResumeLayout (false);

}

#ndregion

[Stathread]

Static void main ()

{

Application.run (New Form1 ());

}

}

}

When you compile and run the code in Listing 2 for the first time, you'll probably get excited that so little code produces a text area with a caret that flashes on and off! After a while, however, you'll notice that our Whiteboard Control Is Not Perfect. Here Is A List of The Control's Imperfections. You can probably add more items to this list.

Pressing Ctrl H fools the control into thinking that the backspace key has been pressed. In most text processing applications, Ctrl H is used to display the Replace dialog box. The arrow keys do not move the caret. Pressing the Control key in Combination with an alphapleric character think an ascii character That Has No Visual Representation (Those with Values ​​Less Than 27). This Will Be Displayed AS A SMALL BOX, AS Shown In Figure 2.

Figure 2. Pressing The Control Character and an alphapleric character at The Same Time Results in A Box.

So, you can see that KeyPress can only handle characters. While this limitation does not create a fuss for small and simple applications, most applications require the proper handling of all keys, not just alphanumeric and punctuation mark keys. The KeyDown event allows you to capture function keys, but not arrow keys. The KeyUp event lets you capture all keys, but this event is only triggered when the user releases the key, by which time it is probably too late to handle the key pressing. The next technique we can resort to is the ProcessDialogKey method, which enables us to capture all keys. Processing All Keys The ProcessDialogKey method in the System.Windows.Forms.Control class is called automatically when a key or a combination of keys on the keyboard is pressed. Unlike the KeyPress event, ProcessDialogKey can capture any key, including the Control keys However, it does not give you the character associated with the key;. it only tells you which key is being pressed For example,. IT Tells you the a key was press, but it doesn '

t tell you whether the character should be the capital or lower-case A. There is a way to check the character case, but this requires more code. For a simpler solution, ProcessDialogKey can be used in conjunction with the KeyPress event. The KeyPress event is invoked after the ProcessDialogKey method is called. Therefore, you can use a flag to tell the KeyPress event handler whether or not it needs to handle a key press. This flag is controlled by the ProcessDialogKey method. If the key press is a combination of control keys and a character key, the ProcessDialogKey will handle it and reset the flag. On the other hand, if the key pressed is a character key, the ProcessDialogKey will set the flag and let the KeyPress event handler take care of the key press . When overriding the ProcessDialogKey method, you should return true when the key was handled and false otherwise. Normally, when your ProcessDialogKey method does not process the key, you call the ProcessDialogKey method of the base class and return whatever value is returned by the base class's ProcessDialogKey method. The ProcessDialogKey method receives one of the System.Windows.Forms.Keys enumeration values ​​as its argument. The Keys enumeration allows a bitwise combination of its values. You should look up the .NET Framework class library reference for the list of values ​​of the Keys enumeration. The argument sent to the ProcessDialogKey method depends on the key (s) being pressed. for instance, if the user pressed the A key, the method will receive Keys. A; if ctrl

S is pressed, the value sent is the bitwise combination of the Control key and the S key. The down arrow sends Keys.Down, the up arrow Keys.Up, and the right and left arrows Keys.Right and Keys.Left respectively. The F1 sends Keys.F1 and Alt F4 sends the bitwise combination of Keys.Alt and Keys.F4. When the Shift key is pressed, the method receives Keys.Shift, enabling you to know whether an upper / lower case character is being sent by the user. The modified version of the WhiteBoard control in Listing 3 overcomes the "flaws" in the code in Listing 1 by via the overriding of the ProcessDialogKey. It uses a flag called keystrokeProcessed also handling control keys to indicate whether or not the KeyPress event handler needs to handle the key press. The code in Listing 3 is similar to the code in Listing 1, except that we now override the ProcessDialogKey method, and that the KeyPress event handler is only executed if the key has not been handled by ProcessDialogkey.The Overriding processd ialogKey in Listing 3 captures the following keys: Arrow keys: move the caret Ctrl R, Ctrl G, Ctrl B:.. change the background color to red, green, and blue, respectively Ctrl Alt R, Ctrl alt G, Ctrl alt B: change the text color to red, green, and blue, respectively Escape:. changes the background color back to white alt F4:. exits the application F1:.. displays a message box You Can Use the code in listing 2 to see the modified control in action. Figure 3 shows the control with a red foreground color.

Figure 3. The Modified Control That Can Handle All Keys

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

New Post(0)