Michael Ebert
Michael Ebert

Reputation: 41

SetConsoleActiveScreenBuffer makes ReadConsole return ERROR_SHARING_VIOLATION

When I call SetConsoleActiveScreenBuffer() with a created buffer, it seems to make ReadConsole stop working with an ERROR_SHARING_VIOLATION. I have checked the handle permissions, and as far as I can tell, they are correct.

If I comment out the SetConsoleActiveScreenBuffer line, the input works perfectly. What might I be doing wrong here?

I have also tried using ReadFile instead of ReadConsole, and getting the input buffer with CreateFile instead of GetStdHandle. Both ways, the same error occurs.

#include <Windows.h>
int main()
{
        void* oldScreenBuffer;
        void* screenBuffer;
        void* inputBuffer;
        char chBuffer[16];
        DWORD numReads;
        int err = 0;
        inputBuffer = GetStdHandle(STD_INPUT_HANDLE);
        //inputBuffer = CreateFile(TEXT("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
        oldScreenBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
        screenBuffer = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
        //commenting out the next line makes input work
        err = SetConsoleActiveScreenBuffer(screenBuffer);
        while(1){
                err = ReadConsole(inputBuffer, chBuffer, 15, &numReads, NULL);
                if(!err){
                        //returns error 32 (ERROR_SHARING_VIOLATION)
                        err=GetLastError();
                }
                if(chBuffer[0]=='q') break;
        }
        SetConsoleActiveScreenBuffer(oldScreenBuffer);
        return 0;
}

Upvotes: 2

Views: 519

Answers (1)

Michael Ebert
Michael Ebert

Reputation: 41

It was the 0 for the sharing mode of the screen buffer. I completely missed that earlier. I changed it to FILE_SHARE_READ | FILE_SHARE_WRITE, and it works. Thanks @Ben.

Upvotes: 2

Related Questions