[C] Hàm xóa màn hình trong VC 6.0

Sưu tầm và trình bày lại:

  • Trần Hán Huy – tranhanhuy.wordpress.com

2 cách này cũng gần tương đương với lệnh clrscr trong turbo C
Ở đây có 2 cách:

Cách 1 : Dùng 1 hàm trong C++

1/ Công dụng :

  • xóa hết màn hình.

2/Thư viện kèm theo:

  • stdlib.h hoặc windows.h

3/ khuyết điểm
Nếu bạn sử dụng hàm màu trong VC. thì sau khi thực hiện lệnh này, cả màn hình sẽ có màu nền trùng với cái hàm nền mà bạn gọi trước đó.
VD:
Trình tự gọi như sau:
– hàm màu có nền xanh
– hàm system(“cls”);
kết quả là cả màn hình có nền màu xanh, không phải nền màu đen như ban đầu nữa

4/ Code

#include "stdlib.h"
void main()
{
	system("cls");
}

Cách 2 : Lập trình 1 hàm thực hiện việc này bằng cách dùng các hàm console

1/ Công dụng :

  • xóa hết màn hình.

2/Thư viện kèm theo:

  • windows.h

3/ khuyết điểm

  • Hàm khá dài, khó nhớ

4/ code hàm

void cls( )
{
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD coordScreen = { 0, 0 }; /* here's where we'll home the
	cursor */
	DWORD cCharsWritten;
	CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
	DWORD dwConSize; /* number of character cells in the current buffer */

	/* get the number of character cells in the current buffer */
	GetConsoleScreenBufferInfo( hConsole, &csbi );

	/* fill the entire screen with blanks */
	FillConsoleOutputCharacter( hConsole, (TCHAR) ' ',dwConSize, coordScreen, &cCharsWritten );

	/* get the current text attribute */
	GetConsoleScreenBufferInfo( hConsole, &csbi );

	/* now set the buffer's attributes accordingly */
	FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten );

	/* put the cursor at (0, 0) */
	SetConsoleCursorPosition( hConsole, coordScreen );
	return;
}

5/ code demo hoàn chỉnh

#include <windows.h>
void cls( )
{
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD coordScreen = { 0, 0 }; /* here's where we'll home the
	cursor */
	DWORD cCharsWritten;
	CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
	DWORD dwConSize; /* number of character cells in the current buffer */

	/* get the number of character cells in the current buffer */
	GetConsoleScreenBufferInfo( hConsole, &csbi );

	/* fill the entire screen with blanks */
	FillConsoleOutputCharacter( hConsole, (TCHAR) ' ',dwConSize, coordScreen, &cCharsWritten );

	/* get the current text attribute */
	GetConsoleScreenBufferInfo( hConsole, &csbi );

	/* now set the buffer's attributes accordingly */
	FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten );

	/* put the cursor at (0, 0) */
	SetConsoleCursorPosition( hConsole, coordScreen );
	return;
}
void main()
{
	printf("Chao mung ban den voi tranhanhuy.wordpress.com");
	cls();
}

Share this:

Like this:

Like

Loading…