Console window interface control design

xiaoxiao2021-03-06  88

Summary: The application development of the text interface is the easiest way to learn C to master the implementation of the interactive system. However, the Visual C C dedicated library does not have the text (character) screen control function supported by TC, for this series of articles from the general control step, the console window, the text (character) control, scrolling and move, cursor, keyboard And a few aspects of the mouse discuss the programming control method of the console window interface. In numerous C development tools, due to the unique advantage of Microsoft itself, it is increasingly accepted by many learners. Obviously, if you still use TC as a development environment, it is not only necessary, and it is not conducive to the transition to the Windows application. However, the C dedicated library of Visual C does not have the text screen (console window) control function supported by TC (the corresponding header file is cono.h). This will inevitably bring a lot of inconvenience to the C learner in text interface design and programming. It is to know that the text interface design is the easiest way to learn C , master the implementation of the interactive system, unlike C Windows graphics interface applications, involving too much knowledge. To this end, this series discusses how to write a C application with aesthetically clear console window interface in the Visual C 6.0 development environment. First, the so-called console application means that those need to maintain some programs with the traditional DOS operating system, while do not need to provide users with a perfect interface. Simply speaking, means the DOS program running in a Windows environment. Once the C console application runs in the Windows 9x / NT / 2000 operating system, one window will pop up. For example, the following procedure: Click the "New Text File" button on the Visual C standard toolbar to open a new document window. Select the File | Save menu or press the shortcut key Ctrl S or click the Save button in the Standard Toolbar to pop up "Save as" file dialog box. Will the file name "Hello.cpp" (note the extension. CPP can not be omitted). Enter the following code in the document window:

#include

void main ()

{

COUT << "Hello, Console!" <

}

Click the "Build" button in the small compilation toolbar or press the F7 button, a dialog box appears, ask if you set this item's folder where the source file is located, click the [Yes] button, the system starts Compilation. Click the "Execute Program" button in the small compilation toolbar or press the Ctrl F5 key to run the programs just now. After the program is run, the window below will pop up.

This is the console window, the most important difference than the traditional DOS screen window: (1) The default console window has a system menu and title, it is a memory buffer window, the buffer size depends on the Windows operating system Distribution; and the DOS screen is a physical window that does not have a Windows window feature, which depends on the memory space allocated by the ROM BIOS. (2) The text operation of the console window is to call the low-level WIN32 APIS, and the text operation of the DOS screen is achieved by calling the 16 (10h) interrupt of the BIOS. (3) The default console window can receive the input information of the keyboard and the mouse. The device driver is managed by Windows, while the DOS screen window needs to call the 33H interrupt when the mouse is received, and the mouse device driver is installed by themselves. Second, the general control step of the console text window In Visual C 6.0, the general programming control step of the console window interface is as follows: Call GetStdHandle Gets the current standard input (stdin) and standard output (STDOUT) device handle. The function origin is: Handle getStdHandle (DWORD NSTDHANDLE); where nstdhandle can be an STD_INPUT_HANDLE (standard input device handle), std_output_handle (standard output device handle) and std_error_handle. It should be noted that the "handle" is the most common concept of Windows. It is usually used to identify Windows resources (such as menus, icons, windows, etc.) and devices. Although the handle can be understood as a pointer variable type, it is not an address pointer in which an object is located, but is used as an index value of the internal table in Windows system. Call the API function control of the related text interface. These functions can be divided into three categories. First, functions for console window operations (including buffers, window foreground characters, and background color, window headers, size, and location, etc.); the other is used for console input and output functions (including character properties operation functions ); Other functions are the last category. Call closeHandle () to close the input and output handle. Note that the header file Windows.h must also be included in the program. Look at a program: #include

#include

#include

void main ()

{

Handle Hout;

Hout = getstdhandle (std_output_handle);

/ / Get standard output device handle

Console_screen_buffer_info binfo; // window information

GetConsolescreenBufferInfo (Hout, & Binfo);

// Get window information

Printf ("/ N / Nthe Soul Selects Her Own Society, / N");

Printf ("Then Shuts the Door; / N");

Printf ("On Her Devine Majority / N");

Printf ("obtrude no more./n");

_Getch ();

Coord POS = {0, 0};

FillconsoleOutputCharacter (hout, '', binfo.dwsize.x * binfo.dwsize.y, pos, null;

/ / Fill characters in the window to get the effect of clearing the screen

CloseHandle (HOUT); // Turn off standard output device handle

}

In the program, COORD and Console_Screen_Buffer_ Info are the type of console structure defined by WinCon.h, whose prototype is as follows:

// coordinate structure typef struct _coord {short x; short y;} coord; // console window information structure type_buffler_info {coord dwsize; // buffer size Coord dwcursorPosition; // Current cursor position Word Wattributes; / / Character attribute small_rect srwindow; // Current window displayed size and location Coord dwMaximumWindowsize; // The largest window buffer size} console_screen_buffer_info; it also needs to be explained, although in C , iostream.h defines CIN and COUT standards. Enter and output flow objects. However, they can only achieve basic input and output operations, but the control of the console window interface is not powerful, and cannot get along with stdio.h and conoe.h, because iostream.h and them are C two sets of different input and output operation methods. Pay special attention when using it. Third, the console window operation is used for the control unit window operation as follows:

Get GetConsoleScreenBufferInfo console window information acquiring GetConsoleTitle console window title ScrollConsoleScreenBuffer mobile data block SetConsoleScreenBufferSize change the specified buffer size setting console window title SetConsoleWindowInfo SetConsoleTitle console window information is provided in the buffer addition, font window, the display mode control function, It is no longer necessary here. One example is followed, the program is as follows:

#include

#include

#include

void main ()

{

Handle hout = getstdhandle (std_output_handle);

/ / Get standard output device handle

Console_screen_buffer_info binfo; // Window buffer information

GetConsolescreenBufferInfo (Hout, Binfo);

// Get window buffer information

CHAR STRTILE [255];

GetConsoletiTe (startle, 255); // Get window titles

Printf ("Current window title is:% S / N", startle);

_Getch ();

SetConsoleTitle ("Console Window Operation"); // Get window titles

_Getch ();

Coord size = {80, 25};

SetConsolescreenBuffersize (hout, size); // Reset the buffer size

_Getch ();

Small_Rect RC = {0, 0, 80-1, 25-1}; // Reset window position and size

SetConsoleWindowInfo (HOUT, TRUE, & RC);

CloseHandle (HOUT); // Turn off standard output device handle

}

It should be noted that the origin coordinates of the console window are (0, 0), and the maximum coordinates are reduced by the buffer size, for example, when the buffer size is 80 * 25, its largest coordinates are (79, 24) . Fourth, the text attribute operation is similar to the DOS character, and the characters in the console window also have corresponding properties. These attributes are divided into three kinds of text, background color, and double-word character set (DBCS) attribute. In fact, we are most concerned about the text color, which can construct a beautiful interface. Color properties are some predefined identifiers:

FOREGROUND_BLUE FOREGROUND_RED red green blue FOREGROUND_GREEN FOREGROUND_INTENSITY strengthen BACKGROUND_BLUE blue background BACKGROUND_GREEN green background BACKGROUND_RED red background BACKGROUND_INTENSITY background color COMMON_LVB_REVERSE_VIDEO strengthen anti-color main functions related to the text attributes are: BOOL FillConsoleOutputAttribute (// padding character attributes HANDLE hConsoleOutput, // handle WORD wAttribute, // text attributes DWORD nLength, // number COORD dwWriteCoord, // start position LPDWORD lpNumberOfAttrsWritten // returns the number of filled); BOOL SetConsoleTextAttribute (// set character attribute WriteConsole like function hANDLE hConsoleOutput, // handle WORD wAttributes // text attributes); BOOL WriteConsoleOutputAttribute (// write property hANDLE hConsoleOutput at a prescribed position, // handle CONST WORD * lpAttribute, // property DWORD nLength, // number COORD dwWriteCoord, // start position LPDWORD lpNumberOfAttrsWritten / / Has written a number; in addition, the text property of obtaining the current console window is obtained by calling the function getConsolescreenBufferInfo, is obtained in the console_screen_ buffer_info structure member Wattributes. V. Text output text output functions are:

BOOL FillConsoleOutputCharacter (// padding character designating data HANDLE hConsoleOutput, // handle TCHAR cCharacter, // character DWORD nLength, // number of characters COORD dwWriteCoord, // start position LPDWORD lpNumberOfCharsWritten // number have been written); BOOL WriteConsole (// Insert the specified number of characters at the current cursor location, // 手柄 const void * lpbuffer, // string dword nnumberofcharstowrite, // character number LPDWORD LPNUMBEROFCHARSWRITTEN, / / ​​Has written a number LPVOID LPRESERVED // Reserved ); BOOL WRITECONSOLEOUTPUT (// Write the character Handle Hconsoleoutput, // handle const char_info * lpbuffer, // data area Coord dwbuffercoord, // start coordinate PSMall_Rect LpwriteRegion / / To write the area); BOOL WRITECONSOLEOUTPUTCHARACTER (// Insert the specified position, insert the specified number of characters Handle Handle Handle HandleOutput, // Handle LPCTSTR LPCHARACTER, // String DWord Nlength, // Character Coord dwwritecoord, // Start location LPDWORD LPNUMBEROFCHARSWRITEN / / The number of writes); It can be seen that the WriteConsoleoutput function function is equivalent to the functionality of SetConsoleTextAttribute and WriteConsole. The WriteConsoleOutputCharacter function is equivalent to the function of SetConsolecursorPosition and WriteConsole. However, pay attention to their differences in specific use. Sixth, text operation examples under the following look at an example program:

#include

Handle Hout;

Void ShadowWindowline (CHAR * STR); // Display a line of characters in a window with shadow effect, window is displayed in place

Void DrawBox (Bool Bsingle, Small_Rect RC); // Draw Border

void main ()

{

Hout = getstdhandle (std_output_handle); // Get standard output device handle

SetConsoleOutputcp (437); // Setting the code page

ShadowWindowLine ("Display a line of words, and center the window with shadow.");

CloseHandle (HOUT); // Turn off standard output device handle

}

Void ShadowWindowLine (Char * STR)

{

Console_screen_buffer_info binfo; // Window buffer information

GetConsolescreenBufferInfo (HOUT, & BINFO); // Get window buffer information

/ / Calculate display window size and location

INT X1, Y1, X2, Y2, Chnum = Strlen (STR);

X1 = (binfo.dwsize.x - chnum) / 2 - 2;

Y1 = binfo.dwsize.y / 2 - 2;

X2 = x1 chnum 4;

Y2 = Y1 5;

Word att1 = background_intensity; // Shadow property word att0 = foreground_red | product_green | Foreground_blue |

Foreground_INTENSITY |

Background_red | background_blue; // Text Properties

Word atttext = foreground_red | foreground_intensity; // Text Properties

// Set shadow

Coord posshadow = {x1 1, y1 1}, poste = {x1, y1};

For (int i = 0; i <5; i ) {

FillconsoleOutputttribute (Hout, Att1, Chnum 4, Posshadow, Null);

Posshadow.y ;

}

// Fill window background

For (i = 0; i <5; i ) {

FillconsoleOutputattribute (Hout, ATT0, Chnum 4, poste, null);

POSTEXT.Y ;

}

// Write text and border

POSTEXT.X = X1 2;

POSTEXT.Y = Y1 2;

WriteconsoleOutputCharacter (Hout, Str, Strlen (Str), Postext, NULL;

Small_Rect RC = {x1, Y1, X2-1, Y2-1};

DrawBox (True, RC);

SetConsoleTextAttribute (Hout, binfo.wattribute); // Restore the original properties

}

Void DrawBox (Bool Bsingle, Small_Rect RC)

{

Char Chbox [6];

IF (BSINGLE) {

Chbox [0] = (char) 0xDA; // Left corner

Chbox [1] = (char) 0xBF; // upper right corner

Chbox [2] = (char) 0xc0; // Left corner

Chbox [3] = (char) 0xD9; // Least right corner

Chbox [4] = (char) 0xc4; // level

Chbox [5] = (char) 0xB3; //

} else {

Chbox [0] = (char) 0xc9; // Left corner

Chbox [1] = (char) 0xBb; // upper right corner

Chbox [2] = (char) 0xc8; // Left corner

Chbox [3] = (char) 0xBC; // Lead right corner

Chbox [4] = (char) 0xcd; // level

Chbox [5] = (char) 0xba; //

}

Coord pos = {rc.left, rc.top};

WriteconsoleOutputcharacter (Hout, & Chbox [0], 1, POS, NULL);

For (pos.x = rc.Left 1; pos.x

WriteconsoleOutputcharacter (Hout, & Chbox [4], 1, POS, NULL);

Pos.x = rc.right;

WriteconsoleOutputcharacter (Hout, & Chbox [1], 1, POS, NULL);

For (pos.y = rc.top 1; pOS.Y

{

Pos.x = rc.left;

WriteconsoleOutputcharacter (Hout, & Chbox [5], 1, POS, NULL); POS.X = rc.right;

WriteconsoleOutputcharacter (Hout, & Chbox [5], 1, POS, NULL);

}

Pos.x = rc.left; pOS.Y = rc.bottom;

WriteconsoleOutputcharacter (Hout, & Chbox [2], 1, POS, NULL);

For (pos.x = rc.Left 1; pos.x

WriteconsoleOutputcharacter (Hout, & Chbox [4], 1, POS, NULL);

Pos.x = rc.right;

WriteconsoleOutputcharacter (Hout, & Chbox [3], 1, POS, NULL);

}

The program operation results are shown below. It should be noted that the above program is different in different character code pages (Code Page). For example, the default code page of the Chinese Windows operating system is Simplified Chinese (936), and a single character having more than 128 at this code page is not displayed in Windows NT / XP. The following table lists the code page that can be used.

Code Page (CODE Page) Description 1258 Vietnamese 1257 Baltic Haiwen 1256 Arabic 1255 Hebrew 1254 Turkish 1253 Greek 1252 Latin (ANSI) 1251 Slavic 1250 中 欧 950 Traditional Chinese 949 Korean 936 Simplified Chinese 932 Japanese 874 Thai 850 uses multiple languages ​​(MS-DOS Latin) 437MS-DOS American / English

7. Scroll and Move ScrollConsolescreenBuffer is an API function that implements scrolling and moving text area. It can move the specified text area to another, and the area that is shot is filled by the specified character. The prototype of the function is as follows:

BOOL ScrollConsoleScreenBuffer (HANDLE hConsoleOutput, // handle CONST SMALL_RECT * lpScrollRectangle, // scroll or move to an area CONST SMALL_RECT * lpClipRectangle, // cropped area COORD dwDestinationOrigin, // new position CONST CHAR_INFO * lpFill // padding character); use This API function also implements the operation of deleting the specified line. Let's take an example, the program is as follows:

#include

#include

#include

Handle Hout;

Void deleteLine (int Row); // Delete a line

Void MoveText (int X, int y, small_rect rc); // Mobile text block area

Void clearscreen (void); // clear screen

void main ()

{

Hout = getstdhandle (std_output_handle); // Get standard output device handle

Word att = foreground_red | product_green | product_INTENSITY | FOREGROUND_INTEN

Background_blue;

// Background is blue, the text color is yellow

SetConsoleTextAttribute (Hout, ATT);

Clearscreen ();

Printf ("/ N / Nthe Soul Selects Her Own Society, / N");

Printf ("Then Shuts the Door; / N");

Printf ("On Her Devine Majority; / N");

Printf ("Obtrude no more./n/n" "; console_screen_buffer_info binfo;

GetConsolescreenBufferInfo (Hout, & Binfo);

Coord endpos = {0, binfo.dwsize.y - 1};

SetConsolecursorPosition (HOUT, ENDPOS); // Set the cursor position

Small_rect rc = {0, 2, 40, 5};

_Getch ();

MoveText (10, 5, rc);

_Getch ();

DeleteLine (5);

CloseHandle (HOUT); // Turn off standard output device handle

}

Void DeleteLine (int Row)

{

Small_Rect Rcscroll, RcClip;

Coord crdest = {0, ROW - 1};

CHAR_INFO CHFILL;

Console_screen_buffer_info binfo;

GetConsolescreenBufferInfo (Hout, & Binfo);

Rcscroll.Left = 0;

Rcscroll.top = row;

Rcscroll.right = binfo.dwsize.x - 1;

Rcscroll.bottom = binfo.dwsize.y - 1;

Rcclip = rcscroll;

Chfill.attributes = binfo.wattribute;

CHFILL.CHAR.ASCIICHAR = '';

ScrollconsolescreenBuffer (Hout, & RCScroll, & rcclip, crdest, & chfill);

}

Void MoveText (int X, int y, small_rect rc)

{

Coord crdest = {x, y};

CHAR_INFO CHFILL;

Console_screen_buffer_info binfo;

GetConsolescreenBufferInfo (Hout, & Binfo);

Chfill.attributes = binfo.wattribute;

CHFILL.CHAR.ASCIICHAR = '';

Scrollconsolescreenbuff (Hout, & RC, NULL, CRDEST, & Chfill);

}

Void Clearscreen (Void)

{

Console_screen_buffer_info binfo;

GetConsolescreenBufferInfo (Hout, & Binfo);

Coord home = {0, 0};

Word att = binfo.wattribute;

Unsigned long size = binfo.dwsize.x * binfo.dwsize.y;

FillconsoleOutputattribute (HOUT, ATT, SIZE, HOME, NULL);

FillconsoleOutputCharacter (HOUT, '', SIZE, HOME, NULL);

}

In the program, the basic principle of the implementation of the deleted row is: first set the crop area and mobile zone to specify the console window area below the row ROW (including the row), and then designate the movement location as (0, Row) -1). Thus, the content exceeding the cropped area is cropped, thereby achieving the purpose of deleting a row. It should be noted that if the cropping area parameter is NULL, the crop area is the entire console window. 8. The cursor in the cursor operation console window reflects the current location of the text insertion. You can change this "current" location through the setConsolecursorPosition function, so that the character (string) output can be controlled. In fact, the size and display or hide of the cursor itself can also be set by the corresponding API function. E.g:

BOOL SetConsoleCursorInfo (// set the cursor information HANDLE hConsoleOutput, // handle CONST CONSOLE_CURSOR_INFO * lpConsoleCursorInfo // cursor information); BOOL GetConsoleCursorInfo (// Get cursor information HANDLE hConsoleOutput, // cursor handle PCONSOLE_CURSOR_INFO lpConsoleCursorInfo // return information); both The function is related to the console_cursor_info structure type, which is defined as follows:

Typedef struct _console_cursor_info {dWord dwsize; // cursor percentage size bool bvisible; // Whether it can be seen} console_cursor_info, * pconsole_cursor_info; need to be explained, the dwsize value reflects the size of the cursor, its value ranges to 1-100; When the cursor is the smallest, it is only a horizontal thin line of the most, when 100, the cursor is the largest, which is a block of characters. Nine, read keyboard information keyboard events typically have character events and button events, and the information included with these events constitutes keyboard information. It is obtained by the API function ReadConsoleinput, which is as follows:

BOOL READCONSOLINPUT (Handle HconSoleinput, // Enter the device handle PINPUT_RECORD LPBUFFER, / / ​​Return Data Record Dword NLENGTH, // To read the number of records lpdword lpnumberofeventsRead // returns the number of read records); where INPUT_RECORD is defined as follows:

typedef struct _INPUT_RECORD {WORD EventType; // event type union {KEY_EVENT_RECORD KeyEvent; MOUSE_EVENT_RECORD MouseEvent; WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent; MENU_EVENT_RECORD MenuEvent; FOCUS_EVENT_RECORD FocusEvent;} Event;} INPUT_RECORD; record structures associated with the keyboard event KEY_EVENT_RECORD defined as follows:

typedef struct _KEY_EVENT_RECORD {BOOL bKeyDown; // TRUE represents a bond press, FALSE, the key release WORD wRepeatCount; // number of keystrokes WORD wVirtualKeyCode; // virtual key codes WORD wVirtualScanCode; // virtual key scan codes union {WCHAR UnicodeChar; // Wide character char asciichar; // ASCII character} uchar; // character dword dwording dwcontrolkeystate; // control key statue} key_event_record; we know, every meaningful key on the keyboard corresponds to a unique scan code, although the scan code can As the logo of the key, it depends on the specific device. Therefore, in the application, use is often a virtual key code that is independent of the specific device. This virtual key code is a keyboard encoding that is not related to the device. In Visual C , the most commonly used virtual key code has been defined in Winuser.h, for example: vk_shift represents the SHIFT key, VK_F1 represents a function key F1, etc. In the above-described structure definition, DWControlKeyState is used to represent the control key state, which can be CapSlock_on (Caps Lock Light), Enhanced_Key, Left_alt_pressed (Press Left Alt Keys), left_ctrl_pressed (Press Left Ctrl Key), Numlock_on (Num Lock Light), Right_alt_Pressed (Press the Right Alt Ke Key), Right_Ctrl_pressed (Press the Right Ctrl Key), Scrollock_on (Scroll Lock Light) and Shift_PRESSED (Press the Shift Key). The following program is to input the characters of the user button to an area of ​​the console window, and when the Num Lock, Caps Lock, and Scroll Lock keys are pressed, the status of the keys in the last line of the console window. #include

Handle Hout;

Handle hin;

Void DrawBox (Bool Bsingle, Small_Rect RC);

Void Clearscreen (Void);

Void Charwindow (char CH, SMALL_RECT RC); // Enter the CH into the specified window

Void ControlStatus (DWORD State); / / / / The status of the control key in the last line

Void deleteTopline (Small_Rect RC); // Delete the top row in the specified window and scroll

void main ()

{

Hout = getstdhandle (std_output_handle); // Get standard output device handle

Hin = getstdhandle (std_input_handle); // Get standard input device handle

Word att = foreground_red | product_green | product_INTENSITY | FOREGROUND_INTEN

Background_blue;

// Background is blue, the text color is yellow

SetConsoleTextAttribute (Hout, ATT);

Clearscreen (); // clear screen

INPUT_RECORD KEYREC;

DWORD State = 0, RES;

CHAR CH;

Small_Rect RC = {20, 2, 40, 12};

DrawBox (True, RC);

Coord pos = {rc.LEFT 1, RC.TOP 1};

SetConsolecursorPosition (HOUT, POS); // Set the cursor position

FOR (;;) // cycle {

Readconsoleinput (Hin, & KeyRec, 1, & Res);

IF (state! = keyrec.event.keyevent.dwcontrolkeystate) {

State = keyrec.event.keyevent.dwcontrolkeystate;

Controlstatus (state);

}

if (KeyRec.EventType == Key_Event) {

if (KeyRec.Event.KeyEvent.wvirtualKeyCode == VK_ESCAPE) BREAK;

/ / Press ESC to exit the loop

KeyRec.Event.KeyEvent.bkeydown) {

CH = keyrec.event.keyevent.uchar.ascialhar;

Charwindow (CH, RC);

}

}

}

POS.x = 0; pOS.Y = 0;

SetConsolecursorPosition (HOUT, POS); // Set the cursor position

CloseHandle (HOUT); // Turn off standard output device handle

CloseHandle (HIN); // Close Standard Enter Equipment Handle

}

Void Charwindow (char CH, SMALL_RECT RC) // Enter the CH into the specified window

{

Static coord chpos = {rc.LEFT 1, RC.TOP 1};

SetConsolecursorPosition (hout, chpos); // Set the cursor position

IF ((CH <0x20) || (CH> 0x7e)) Return;

WriteconsoleOutputcharacter (Hout, & Ch, 1, Chpos, NULL);

IF (chpos.x> = (rc.right-1))

{

chpos.x = rc.left;

Chpos.y ;

}

IF (chpos.y> (rc.bottom-1))

{

Deletetopline (RC);

Chpos.y = rc.bottom-1;

}

Chpos.x ;

SetConsolecursorPosition (hout, chpos); // Set the cursor location

}

Void ControlStatus / / The status of the control key in the last line

{

Console_screen_buffer_info binfo;

GetConsolescreenBufferInfo (Hout, & Binfo);

Coord home = {0, binfo.dwsize.y-1};

Word att0 = background_intensity;

Word att1 = foreground_green | product_intensity | background_red;

FillconsoleOutputattribute (Hout, Att0, binfo.dwsize.x, home, null);

FillconsoleOutputCharacter (Hout, '', binfo.dwsize.x, home, null);

SetConsoleTextAttribute (Hout, ATT1);

Coord stapos = {binfo.dwsize.x-16, binfo.dwsize.y-1};

SetConsolecursorPosition (HOUT, Stapos);

IF (State & Numlock_on)

Writeconsole (HOUT, "NUM", 3, NULL, NULL); Stapos.x = 4;

SetConsolecursorPosition (HOUT, Stapos);

IF (State & Capslock_on)

Writeconsole (HOUT, "CAPS", 4, NULL, NULL);

Stapos.x = 5;

SetConsolecursorPosition (HOUT, Stapos);

IF (State & Scrollock_on)

Writeconsole (HOUT, "Scroll", 6, NULL, NULL);

SetConsoleTextAttribute (Hout, binfo.wattribute); // Restore the original properties

SetConsolecursorPosition (hout, binfo.dwcursorPosition); // Restore the original cursor location

}

Void deleTopline (Small_Rect RC)

{

Coord crdest;

CHAR_INFO CHFILL;

Small_rect rcclip = rc;

Rcclip.Left ; rcclip.right--;

RcClip.top ; rcclip.bottom -;

CRDEST.X = rcclip.left;

CRDEST.Y = rcclip.top - 1;

Console_screen_buffer_info binfo;

GetConsolescreenBufferInfo (Hout, & Binfo);

Chfill.attributes = binfo.wattribute;

CHFILL.CHAR.ASCIICHAR = '';

ScrollconsolescreenBuffer (Hout, & RCCLIP, & RCCLIP, CRDEST, & Chfill);

}

The program operation results are shown below:

X. Read the mouse information is similar to the reading keyboard information method, and the mouse information is also obtained through ReadConsoleInput, and its mouse_event_record has the following definition:

typedef struct _MOUSE_EVENT_RECORD {COORD dwMousePosition; // current mouse position DWORD dwButtonState; // mouse button state DWORD dwControlKeyState; // keyboard control key state DWORD dwEventFlags; // Event Status} MOUSE_EVENT_RECORD; wherein, dwButtonState reflects the user presses the mouse button cases, it may be: FROM_LEFT_1ST_BUTTON_PRESSED (leftmost button), RIGHTMOST_BUTTON_PRESSED (rightmost button), FROM_LEFT_2ND_BUTTON_PRESSED (second from the left button), FROM_LEFT_3RD_BUTTON_PRESSED (third from left button) and FROM_LEFT_4TH_BUTTON_PRESSED (fourth button from the left). DWEventFlags represents an event of mouse, such as Double_Click, mouse_moved (mobile), and mouse_wheeled (roller scrolling, only for Windows 2000 / XP). The meaning of dwcontrolKeyState is the same. Let's take an example. This example can display the current location of the mouse on the last row of the console window. If you click the left mouse button, write a character 'a' at the current location, if you double your mouse, please, the program terminates. The specific code is as follows:

#include #include #include handle hout; handle hin; void clearscreen (void); Void DispmousePos (COORD POS); // Show mouse position void main in the last line () {hOut = GetStdHandle (STD_OUTPUT_HANDLE); // Get standard output device handle hIn = GetStdHandle (STD_INPUT_HANDLE); // Get the standard input device handle WORD att = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE; // blue background, text Color is yellow setconsoletexttattribute (hout, att); clearscreen (); // clear screen input_record mouserec; dword stat = 0, res; for (;;) // cycle {readconsoleInput (HIN, & mouseRec, 1, & res); if (mouseRec.EventType == mOUSE_EVENT) {if (mouseRec.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK) break; // double click to exit the loop pos = mouseRec.Event.MouseEvent.dwMousePosition; DispMousePos ( pos); if (mouseRec.Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) FillConsoleOutputCharacter (hOut, 'A', 1, pos, NULL);}} pos.X = 0; pos.Y = 0; SetConsoleCursorPosition (hOut, pos ); // Set the cursor position CloseHandle (HOUT) ; // Close the standard output device handle CloseHandle (HIN); // Close Standard input device handle} Void DispmousePos (Coord POS) // Display mouse position in the last line {Console_Screen_Buffer_info Binfo; GetConsolescreenBufferInfo (Hout, & Binfo); coord home = { 0, bInfo.dwSize.Y-1}; WORD att0 = BACKGROUND_INTENSITY; FillConsoleOutputAttribute (hOut, att0, bInfo.dwSize.X, home, NULL); FillConsoleOutputCharacter (hOut, '', bInfo.dwSize.X, home, NULL) CHAR S [20]; Sprintf (s, "x =% 2lu, y =% 2lu", pos.x, pos.y); setconsoletextAttribute (Hout, ATT0); SetConsolecursorPosition (HOUT, HOME); WriteConsole (HOUT, S, Strlen (s), null, null;

SetConsoleTextAttribute (hOut, bInfo.wAttributes); // restore the original properties SetConsoleCursorPosition (hOut, bInfo.dwCursorPosition); // restore the original cursor position} void ClearScreen (void) {CONSOLE_SCREEN_BUFFER_INFO bInfo; GetConsoleScreenBufferInfo (hOut, & bInfo); COORD home = {0, 0}; unsigned long size = bInfo.dwSize.X * bInfo.dwSize.Y; FillConsoleOutputAttribute (hOut, bInfo.wAttributes, size, home, NULL); FillConsoleOutputCharacter (hOut, '', size, home, NULL );} The program operations are as follows: 11. In summary, the WIDOWS API function using the console window can design a simple and beautiful text interface, so that in deep learning of the Visual C 6.0 development environment to learn C and text interface design becomes one Amazing event. Of course, the design of the text interface requires certain methods and techniques, limited to space, and no longer elaborate here.

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

New Post(0)