看了一下如何执行(据说)简单的任务:清除cmd.exe控制台窗口,并发现仅使用system('cls');是错误的(参考"每个复杂问题都有一个清晰、简单且错误的解决方案" )。我尝试将win32代码复制并粘贴到函数中,但出现编译错误。然后,我找到了以下函数, 但不知道如何使用变量调用它,而不会产生错误消息。
我的问题是:如何设置控制台句柄以传递给`cls`函数?
编辑:请注意,我不希望仅通过调用system来调用/调用cls或clear命令,这是this question中大多数答案建议的方法。
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
/* Standard error macro for reporting API errors */
#define PERR(bSuccess, api){ if(!(bSuccess)) printf("%s:Error %d from %s \
on line %d\n", __FILE__, GetLastError(), api, __LINE__); }
HWND GetConsoleHwnd(void) {
#define MY_BUFSIZE 1024 // Buffer size for console window titles.
HWND hwndFound; // This is what is returned to the caller.
char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
// Fetch current window title.
GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
// Format a "unique" NewWindowTitle.
wsprintf(pszNewWindowTitle,"%d/%d", GetTickCount(), GetCurrentProcessId());
// Change current window title.
SetConsoleTitle(pszNewWindowTitle);
// Ensure window title has been updated.
Sleep(40);
// Look for NewWindowTitle.
hwndFound=FindWindow(NULL, pszNewWindowTitle);
// Restore original window title.
SetConsoleTitle(pszOldWindowTitle);
return(hwndFound);
}
void cls( HANDLE hConsole ) {
COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
BOOL bSuccess;
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 */
bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi );
PERR( bSuccess, "GetConsoleScreenBufferInfo" );
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
/* fill the entire screen with blanks */
bSuccess = FillConsoleOutputCharacter( hConsole, (TCHAR) ' ',
dwConSize, coordScreen, &cCharsWritten );
PERR( bSuccess, "FillConsoleOutputCharacter" );
/* get the current text attribute */
bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi );
PERR( bSuccess, "ConsoleScreenBufferInfo" );
/* now set the buffer's attributes accordingly */
bSuccess = FillConsoleOutputAttribute( hConsole, csbi.wAttributes,
dwConSize, coordScreen, &cCharsWritten );
PERR( bSuccess, "FillConsoleOutputAttribute" );
/* put the cursor at (0, 0) */
bSuccess = SetConsoleCursorPosition( hConsole, coordScreen );
PERR( bSuccess, "SetConsoleCursorPosition" );
return;
}
int main (void) {
// why does this fail?
HWND cons = GetConsoleHwnd();
cls(cons);
return 0;
}
我的问题是:如何设置控制台句柄以传递给`cls`函数?
编辑:请注意,我不希望仅通过调用system来调用/调用cls或clear命令,这是this question中大多数答案建议的方法。
AllocConsole
。然而,普遍存在一个误解,即编程主要是通过在互联网上找到片段并将它们拼凑在一起来完成的,而不知道自己在做什么。抱歉给你带来坏消息,这样行不通。 - IInspectable