控制台中的屏幕缓冲区

时间:2011-02-28 07:12:07

标签: c console-application

我正在创建一个用于读写的控制台应用程序。我已经使用“CreateConsoleScreenBuffer”创建了用于读写的屏幕缓冲区。我要写入控制台但无法读取用户的输入。我添加了代码。

#include <windows.h>
#include <stdio.h>

#define BUFSIZE 4096
int main(void)
{
   CHAR chBuf[BUFSIZE];
   DWORD dwRead, dwWritten,dwFlags,fdwMode;
   HANDLE hWrite;
   WORD wOldColorAttrs,len;
   SECURITY_ATTRIBUTES saAttr;
   FILE *FD = NULL;
   FD = fopen ( "temp7.txt","w+");

   AllocConsole();
   LPSTR lpszPrompt1 = "********** Hi I am here ************* \n";

   hWrite = CreateConsoleScreenBuffer(GENERIC_READ|GENERIC_WRITE,FILE_SHARE_WRITE|FILE_SHARE_READ,NULL,CONSOLE_TEXTMODE_BUFFER,NULL);

   SetConsoleActiveScreenBuffer(hWrite);

   GetConsoleMode(hWrite,&dwFlags);

   fdwMode = dwFlags & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
   if (!SetConsoleMode(hWrite, fdwMode))
   {
      MessageBox(NULL, TEXT("SetConsoleMode"), TEXT("Console Error"), MB_OK);
      return 1;
   }

   fprintf(FD," ********** Flag for Get Console is %d ************ \n",dwFlags);

   if ( WriteConsole(hWrite,lpszPrompt1,strlen(lpszPrompt1),len,NULL)!= 0)
   {
    fprintf(FD," ********** Buffer Written %d and %d ************* \n",GetLastError(),hWrite);
    MessageBox(NULL, TEXT("SetConsoleMode"), TEXT("Write Error"), MB_OK);
        return 1;
   }
   for (;;)
   {
    if ( ReadFile(hWrite,chBuf,255,&dwRead,NULL)!= 0 )    // not overlapped
    {
       fprintf(FD," ********** Error Receiving User Buffer %d and %d ************* \n",GetLastError(),hWrite);
       break;
    }
    fprintf(FD," ********** Following is the Buffer (%d) Received from user ************* \n",dwRead);
    fprintf(FD," %s", chBuf);
    if( chBuf[0]== 'q')
    {
        fprintf(FD," ********** User Pressed Quit************* \n");
        break;
    }

    chBuf[0]='\0';
   }
   getch();
   return 0;
}

以下是输出:

 ********** Flag for Get Console is 3 ************ 
 ********** Following is the Buffer (0) Received from user ************* 
 # ********** Following is the Buffer (0) Received from user ************* 

请帮忙

〜约翰尼

2 个答案:

答案 0 :(得分:0)

你应该空终止用户输入的字符串,ReadFile不会自动执行此操作

 chBuf[ dwRead ] = 0;

答案 1 :(得分:0)

感谢您的投入。我发现了错误。 CreateConsoleScreenBuffer可用于输出缓冲区。此外,Windows提供了一种使用CONIN $和cONOUT $创建文件的方法,它只是控制台输入和输出缓冲区文件。即使重定向标准的输入和输出,该缓冲区也将属于处理控制台。

 hRead=CreateFile("CONIN$",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ,0,OPEN_EXISTING,0,0);
 hWrite=CreateFile("CONOUT$",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ,0,OPEN_EXISTING,0,0);

此致 杜琪峰