Console window Interface Programming Control (1)

Source: Internet
Author: User

Console Application Development on the text interface is the easiest way to thoroughly learn C ++ and master the implementation methods of the interactive system. However, the C ++ library of Visual C ++ does not have the text (character) screen control function supported by TC, for this reason, this series of articles discusses the console window interface programming control methods from the following aspects: general control steps, console window operations, text (character) control, scrolling and moving, cursor, keyboard and mouse.

Among the many c ++ development tools, due to Microsoft's unique advantages, Visual C ++ has become increasingly accepted by many learners. Obviously, if TC is used as a development environment, it is not only unnecessary, but also not conducive to the transition to Windows application development. However, the C ++ library of Visual C ++ does not have the text screen (console window) control function supported by TC (the corresponding header file is conio. h ). This will inevitably cause a lot of inconvenience to C ++ learners in text interface design and programming. You must know that text interface design is the simplest way to thoroughly learn C ++ and master the implementation method of the interactive system. It is not like the Windows graphic interface application of C ++, too much knowledge is involved. To this end, this series of articles will discuss how to write c ++ applications with beautiful and clear Console window interfaces in the Visual C ++ 6.0 development environment.

I. Overview

A console application is a program that requires compatibility with a traditional DOS operating system without providing a complete interface for users. Simply put, it refers to the DOS program running in windows. Once the C ++ console application runs in the Windows 9x/NT/2000 operating system, a window is displayed. For example, the following process:

Click the new text file button on the Visual C ++ Standard toolbar to open a new document window.

Select the file | save menu, press the shortcut key Ctrl + S, or click the Save button on the Standard toolbar to bring up the "Save as" file dialog box. Set the file name to "Hello. cpp" (note that the extension. cpp cannot be omitted ).

Enter the following code in the document window:

# Include
Void main ()
{
Cout <"Hello, console! "<}

Click the "build" button in the mini-compilation toolbar or press the F7 key. The system displays a dialog box asking whether to set the working folder of the project to the folder where the source file is located, and click the [Yes] button, the system starts compiling.

Click the Execute Program button in the mini compilation toolbar or press Ctrl + F5 to run the program just now.

After the program is running, a window pops up.

 

This is the console window, the main difference compared with the traditional dos screen window is:

(1) The default Console window has system menus and titles. It is a memory buffer window. The buffer size depends on the distribution of Windows operating systems. The dos screen is a physical window, the Windows window feature is not available. The size depends on the memory space allocated by the rom bios.

(2) The text operation in the console window calls the lower-layer Win32 APIs, while the text operation on the DOS screen is implemented by calling the BIOS 16 (10 h) interrupt.

(3) The default Console window can receive keyboard and mouse input information. The device driver is managed by windows, and the DOS screen window needs to call H for interruption when receiving mouse information, the driver of the mouse device is installed by yourself.

II. General control steps of the console text window

In Visual C ++ 6.0, the general programming control steps on the console window interface are as follows:

Call getstdhandle to obtain the current stdin and stdout device handle. Function prototype:

Handle getstdhandle (DWORD nstdhandle );

Among them, nstdhandle can be std_input_handle (standard input device handle), std_output_handle (standard output device handle), and std_error_handle (standard error handle ). It should be noted that "handle" is the most common concept in windows. It is usually used to identify windows resources (such as menus, icons, windows, etc.) and devices and other objects. Although the handle can be understood as a pointer variable type, it is not the address pointer of the object, but used as the index value of the internal table in windows.

Call the API functions controlled by the relevant text interface. These functions can be divided into three types. 1. functions used for Console window operations (including window buffer size, window foreground characters and background color, window title, size and position ); second, the functions used for console input and output (including character attribute operation functions); other functions are the last class.

Call closehandle () to close the input/output handle.

Note: The program must also contain the header file windows. h. Let's look at a program:

# Include
# Include
# Include
Void main ()
{
Handle Hout;
Hout = getstdhandle (std_output_handle );
// Get the handle of the standard output device
Lele_screen_buffer_info binfo; // window information
Getconsolescreenbufferinfo (Hout, & binfo );
// Obtain 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 in characters in the window to get the screen clearing effect
Closehandle (Hout); // closes the handle of the standard output device.
}

In the program, coord and console_screen_buffer _ INFO are console struct types defined by wincon. H. Their prototype is as follows:

// Coordinate struct
Typedef struct _ coord {
Short X;
Short y;
} Coord;

// Structure of console window information
Typedef struct _ lele_screen_buffer_info {
Coord dwsize; // buffer size
Coord dwcursorposition; // current cursor position
Word wattributes; // character attribute
Small_rect srwindow; // the size and position of the current window
Coord dwmaximumwindowsize; // maximum window buffer size
} Lele_screen_buffer_info;

In C ++, iostream. h defines the standard input and output stream objects of CIN and cout. However, they can only implement basic input and output operations, but cannot control the console window interface, and cannot be used with stdio. H and conio. H is friendly because iostream. H is different from C ++ in terms of input/output operations.

3. Console window operations

The API functions used for Console window operations are as follows:

 

 

 

 

 

Getconsolescreenbufferinfo
Getconsoletitle: Get the title of the console window
Scrollconsolescreenbuffer moves data blocks in the buffer zone
Setconsolescreenbuffersize: Change the specified buffer size
Setconsoletitle: Set the title of the console window
Setconsolewindowinfo: set console window information

In addition, there are Window Font, display mode and other control functions, which are not described here. The following is an example:

# Include
# Include
# Include
Void main ()
{
Handle Hout = getstdhandle (std_output_handle );
// Get the handle of the standard output device
Lele_screen_buffer_info binfo; // window buffer Information
Getconsolescreenbufferinfo (Hout, binfo );
// Obtain window buffer Information
Char strtitle [255];
Getconsoletitle (strtitle, 255); // obtain the window title
Printf ("current window title: % s/n", strtitle );
_ Getch ();
Setconsoletitle ("Console window operation"); // obtain the window title
_ Getch ();
Coord size = {80, 25 };
Setconsolescreenbuffersize (Hout, size); // reset the buffer size
_ Getch ();
Small_rect rc = {0, 0-1, 25-1}; // reset the window position and size
Setconsolewindowinfo (Hout, true, & rc );
Closehandle (Hout); // closes the handle of the standard output device.
}

It must be noted that the origin coordinates of the console window are (0, 0), and the maximum coordinates are the buffer size minus 1. For example, when the buffer size is 80*25, the maximum coordinate is (79, 24 ).

Iv. Text attribute operations

Similar to DoS characters, the characters in the console window also have corresponding properties. These attributes are divided into three types: Text foreground color, background color, and double-byte character set (DBCS) attributes. In fact, we are most concerned with text color, which can create beautiful interfaces. Color attributes are some predefined identifiers:

Foreground_blue
Foreground_green green
Foreground_red
Foreground_intensity enhanced
Background_blue background
Background_green green background
Background_red background
Background_intensity enhanced background color
Common_lvb_reverse_video reversed color

Main functions related to text attributes include:

Bool fillconsoleoutputattribute (// fill character attribute
Handle hconsoleoutput, // handle
Word wattribute, // text attribute
DWORD nlength, // number
Coord dwwritecoord, // start position
Lpdword lpnumberofattrswritten // return the number of filled items
);

Bool setconsoletextattribute (// set the character attributes of functions such as writeconsole
Handle hconsoleoutput, // handle
Word wattributes // text attributes
);

Bool writeconsoleoutputattribute (// write the attribute at the specified position
Handle hconsoleoutput, // handle
Const word * lpattribute, // attribute
DWORD nlength, // number
Coord dwwritecoord, // start position
Lpdword lpnumberofattrswritten // Number of writes
);

In addition, the text attribute of the current Console window is obtained in wattributes, a member of the console_screen _ buffer_info structure, by calling the getconsolescreenbufferinfo function.

V. Text output

Text output functions include:

Bool fillconsoleoutputcharacter (// enter the character of the specified data
Handle hconsoleoutput, // handle
Tchar ccharacter, // character
DWORD nlength, // number of characters
Coord dwwritecoord, // start position
Lpdword lpnumberofcharswritten // Number of writes
);

Bool writeconsole (// insert a specified number of characters at the current cursor position
Handle hconsoleoutput, // handle
Const void * lpbuffer, // string
DWORD nnumberofcharstowrite, // number of characters
Lpdword lpnumberofcharswritten, // Number of writes
Lpvoid lpreserved // Reserved
);

Bool writeconsoleoutput (// write Attribute-specific characters to a specified region
Handle hconsoleoutput, // handle
Const char_info * lpbuffer, // character data Zone
Coord dwbuffersize, // Data Partition size
Coord dwbuffercoord, // start Coordinate
Psmall_rect lpwriteregion // area to be written
);

Bool writeconsoleoutputcharacter (// insert a specified number of characters at a specified position
Handle hconsoleoutput, // handle
Lptstr lpcharacter, // string
DWORD nlength, // number of characters
Coord dwwritecoord, // start position
Lpdword lpnumberofcharswritten // Number of writes
);

The writeconsoleoutput function is equivalent to the setconsoletextattribute and writeconsole functions. The writeconsoleoutputcharacter function is equivalent to setconsolecursorposition (set the cursor position) and writeconsole. But pay attention to their differences in specific use.
 

Vi. Text operation example

The following is a sample program:

 

 

 

# Include <windows. h>
Handle Hout;
Void shadowwindowline (char * Str); // a line of characters is displayed in the shadow window, and the window is centered.
Void drawbox (bool bsingle, small_rect RC); // draw a border
Void main ()
{
Hout = getstdhandle (std_output_handle); // gets the handle of the standard output device.
Setconsoleoutputcp (437); // sets the code page.
Shadowwindowline ("display a line of words, and center the window with shadow .");
Closehandle (Hout); // closes the handle of the standard output device.
}

Void shadowwindowline (char * Str)
{
Lele_screen_buffer_info binfo; // window buffer Information
Getconsolescreenbufferinfo (Hout, & binfo); // obtain window buffer Information
// Calculate the size and position of the displayed window
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 | foreground_green | foreground_blue |
Foreground_intensity |
Background_red | background_blue; // text attribute

Word atttext = foreground_red | foreground_intensity; // text attribute
// Set the shadow.
Coord posshadow = {x1 + 1, Y1 + 1}, postext = {x1, Y1 };
For (INT I = 0; I <5; I ++ ){
Fillconsoleoutputattribute (Hout, att1, chnum + 4, posshadow, null );
Posshadow. y ++;
}
// Fill in the window background
For (I = 0; I <5; I ++ ){
Fillconsoleoutputattribute (Hout, att0, chnum + 4, postext, 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. wattributes); // restore the original attribute
}

Void drawbox (bool bsingle, small_rect RC)
{
Char chbox [6];
If (bsingle ){
Chbox [0] = (char) 0xda; // point in the upper left corner
Chbox [1] = (char) 0xbf; // point in the upper right corner
Chbox [2] = (char) 0xc0; // point in the lower left corner
Chbox [3] = (char) 0xd9; // point in the lower right corner
Chbox [4] = (char) 0xc4; // horizontal
Chbox [5] = (char) 0xb3; // straight
} Else {
Chbox [0] = (char) 0xc9; // point in the upper left corner
Chbox [1] = (char) 0xbb; // point in the upper right corner
Chbox [2] = (char) 0xc8; // point in the lower left corner
Chbox [3] = (char) 0xbc; // point in the lower right corner
Chbox [4] = (char) 0xcd; // horizontal
Chbox [5] = (char) 0xba; // straight
}
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 );
}
 

Shows the program running result.
 
It should be noted that the above programs display different results on different character code pages. For example, if the default code page of a Chinese Windows operating system is simplified Chinese (936), a single character whose value exceeds 128 cannot be displayed on Windows NT/XP. The following table lists available code pages.

Code Page Description
1258 Vietnamese
1257 Baltic text
1256 Arabic
1255 Hebrew
1254 Turkish
1253 Greek
1252 Latin (ANSI)
1251 Slavic
1250 moderate Owen
950 traditional Chinese
Korean 949
Simplified Chinese 936
932 Japanese
874 Thai
850 use multiple languages (MS-DOS Latin)
437 MS-DOS American/English

Article Source: http://www.diybl.com/course/3_program/c++/cppsl/2008829/138699_2.html

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.