How to Manually Write to Console G++ Linux W/O printf / cout? - c++

I want to follow https://www.youtube.com/watch?v=xW8skO7MFYw&t=357s tutorial, but at one point the author manually allocates the console to be more efficient. He uses what looks like Windows specific instructions, but I want to achieve the same thing on Linux. I am on Debian 9.8 and using g++6.3. This is the code I want to duplicate on my Linux end.
#include <stdio.h>
#include <Windows.h>
int nScreenWidth = 120;
int nScreenHeight = 40;
wchar_t *screen = new wchar_t[nScreenWidth*nScreenHeight];
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole);
DWORD dwBytesWritten = 0;
I already tried finding a solution to this and I couldn't find anything. Thanks I appreciate the help

Related

HRESULT 0x8876086c D3DERR_INVALIDCALL with DirectX9 pretty much following the documentation example

So i wanna draw an overlay over another window, but im getting no real runtime error the visual Studio debugging tools tell me that the result of
HRESULT res = object->CreateDeviceEx(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWND, D3DCREATE_HARDWARE_VERTEXPROCESSING, &params, NULL, &device);
is 0x8876086c. So here are the snippets of my code that are important and lead to this error(D3DERR_INVALIDCALL), which leads to the device being a nullpointer, which means i can't do anything with it.
I couldn't really figure out what led to this as i pretty much followed the documentation
int Paint::init(HWND hWND) {
if (FAILED(Direct3DCreate9Ex(D3D_SDK_VERSION, &object))) {
exit(1);
}
ZeroMemory(&params, sizeof(params));
params.BackBufferWidth = width;
params.BackBufferHeight = height;
params.Windowed = true;
params.hDeviceWindow = hWND;
params.MultiSampleQuality = D3DMULTISAMPLE_NONE;
params.BackBufferFormat = D3DFMT_A8R8G8B8;
params.EnableAutoDepthStencil = TRUE;
params.AutoDepthStencilFormat = D3DFMT_D16;
HRESULT res = object->CreateDeviceEx(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWND, D3DCREATE_HARDWARE_VERTEXPROCESSING, &params, NULL, &device);
and in the header file:
class Paint {
private:
IDirect3D9Ex* object = NULL;
IDirect3DDevice9Ex* device = NULL;
DWORD behaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING;
D3DPRESENT_PARAMETERS params;
ID3DXFont* font = 0;
HWND TargetHWND;
int width, height;
int init(HWND(hWND));
}
D3DPRESENT_PARAMETERS params = {};
// Use Win32 BOOL "TRUE" instead of C++ "true"
params.Windowed = TRUE;
params.hDeviceWindow = m_window;
// params.BackBufferWidth, BackBufferHeight are ignored for Windowed = TRUE
// For Windowed = TRUE, use params.BackBufferFormat = D3DFMT_UNKNOWN, which is zero.
// For params.BackBufferCount zero is assumed to be 1, but best practice
// would be to set it
params.BackBufferCount = 1;
// You used D3DMULTISAMPLE_NONE for the MultiSampleQuality instead of MultiSampleType.
// It's all zero anyhow.
params.EnableAutoDepthStencil = TRUE;
params.AutoDepthStencilFormat = D3DFMT_D16;
// --->>> This is the actual bug: there is no valid SwapEffect that has a value of zero <<<---
params.SwapEffect = D3DSWAPEFFECT_DISCARD;
You are making the assumption that the Direct3D9 device supports D3DCREATE_HARDWARE_VERTEXPROCESSING, but you haven't validated it actually supports it. That said, D3DCREATE_SOFTWARE_VERTEXPROCESSING has known performance issues on Windows 10 so you should probably just require HW anyhow.
You should not be using legacy Direct3D9 or Direct3D9Ex for new projects. It's mostly emulated on newer versions of Windows, has lots of strange behaviors, and is almost 20 years old at this point. There's no support for the Direct3D 9 debug device on Windows 8.x or Windows 10. You should consider Direct3D 11 as a much better starting place for developers new to DirectX.

WriteConsoleOutputCharacter in c++ loads of ?s on console

So I am following this tutorial here https://www.youtube.com/watch?v=xW8skO7MFYw and I am new to accessing console buffer and that. I started debugging when I realized my console looked like this https://ibb.co/896tGGL when I ran it. And I narrowed it down to this line of code
WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenheight, { 0,0 }, &dwBytesWritten);
the values in this are set to:
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
wchar_t* screen = new wchar_t[nScreenWidth * nScreenheight];
int nScreenWidth = 120;
int nScreenheight = 40;
DWORD dwBytesWritten = 0;
All the parts of your code that say
screen[y * nScreenWidth] = something;
should be
screen[y * nScreenWidth + x] = something;
And of course you need to loop to set the x coordinate.
If you look carefully you can actually see the # on the left edge of your screen. That's because you missed the x ccordinate out of your calculations.

how to issue command to cmd prompt using WriteConsoleOutputCharacter() console function c++

i want to issue commands to cmd prompt through WriteConsoleOutputCharacter(), i have tried the following code but did not respond any result just it write "Dir" at x y cord..
I don't know whether it is possible or not, if answer is not then suggest any other solution same like this. This program is a bit part of my application.
int main()
{
HANDLE hStdout;
processHandler* process = new processHandler();
process->start("cmd.exe");
AttachConsole(process->getPID());
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coordScreen = { 0, 0 };
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
coordScreen.X=csbi.dwCursorPosition.X;
coordScreen.Y=csbi.dwCursorPosition.Y;
WriteConsoleOutputCharacter( hConsole,"dir",3,coordScreen,&cCharsWritten );
coordScreen.X+=3;
SetConsoleCursorPosition(hConsole,coordScreen);
getch();
}

Windows function ChoosePixelFormat returns ERR_OLD_WIN_VERSION on windows 7

I'm trying to teach myself the win32 API by making a window and attaching an OpenGL context to it. In order to fetch the appropriate pixel format a call to ChoosePixelFormat must be made which should return a pixel format that the system supports and best meets my needs. When I check for errors everything goes smoothly until this function is called which stops execution and logs error 1150-ERR_OLD_WIN_VERSION which is supposed to mean that my version of windows does not support this function. This is obviously not the case and msdn confirms that this function runs on all versions of windows since windows 2000. Right now I'm running windows 7 x64 on my desktop and I made sure my video driver and os were fully updated. Lots of people seem to have had trouble with the pixel format functions but I have not found any with my problem so I decided to post here for help. Here is my full code; I have not tested it on any machines other than my own.
WinMain.cpp (the only non-default msvc lib this is linked with is opengl32.lib)
#include"Display.h"
#include<iostream>
#include<fstream>
MSG message;
DWORD error;
int status;
LRESULT CALLBACK WndProc(HWND hWindow, UINT message, WPARAM wParam, LPARAM lParam)
{ switch(message)
{case WM_CREATE:
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
switch(wParam)
{case VK_ESCAPE:
PostQuitMessage(0);
return 0;}}
return DefWindowProc(hWindow, message, wParam, lParam);}
int MainLoop(Display d)
{
while((status = PeekMessage(&message, d.hWindow, 0, 0, PM_REMOVE)) != 0)
{
if (status == -1)
{
return -1;
}
DispatchMessage(&message);
}
return 0;
}
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
std::ofstream file("log.txt", std::ios::trunc);
Display window("TEST", hInstance, WndProc, 50, 50, 50, 50, NULL, NULL);
if(window.status == -1)
{ error = GetLastError();
file << error;
return 1;}
ShowWindow(window.hWindow, SW_SHOWNORMAL);
EnableWindow(window.hWindow, true);
MainLoop(window);
return 0;
}
Display.h (problem occurs in the class constructor)
#include <Windows.h>
class Display
{public:
Display(const char*, HINSTANCE, WNDPROC, int, int, int, int, DWORD, DWORD);
~Display();
HWND hWindow;
int status;
private:
WNDCLASSEX data;
HDC hDeviceContext;
HGLRC hGLContext;
PIXELFORMATDESCRIPTOR PFD;
int x, y, width, height;};
Display::Display(const char* title, HINSTANCE InstanceHandle, WNDPROC WindowProcedure, int ScreenPositionX, int ScreenPositionY, int WindowWidth, int WindowHeight, DWORD StyleFlags, DWORD ExtendedStyleFlags)
{ data.cbSize = sizeof(WNDCLASSEX);
data.style = CS_OWNDC;
data.lpfnWndProc = WindowProcedure;
data.cbClsExtra = 0;
data.cbWndExtra = 0;
data.hInstance = InstanceHandle;
data.hIcon = NULL;
data.hCursor = NULL;
data.hbrBackground = NULL;
data.lpszMenuName = NULL;
data.lpszClassName = "WIN1";
data.hIconSm = NULL;
RegisterClassEx(&data);
hWindow = CreateWindowEx(ExtendedStyleFlags, data.lpszClassName, title, StyleFlags | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, x = ScreenPositionX, y = ScreenPositionY, width = WindowWidth, height = WindowHeight, NULL, NULL, InstanceHandle, NULL);
PFD.nSize = sizeof(PIXELFORMATDESCRIPTOR);
PFD.nVersion = 1;
PFD.iPixelType = PFD_TYPE_RGBA;
PFD.iLayerType = PFD_MAIN_PLANE;
PFD.dwVisibleMask = 0;
PFD.dwLayerMask = 0;
PFD.dwDamageMask = 0;
PFD.dwFlags = PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL;
PFD.cAuxBuffers = 0;
PFD.bReserved = 0;
PFD.cColorBits = 24;
PFD.cAccumBits = 0;
PFD.cDepthBits = 32;
PFD.cStencilBits = 0;
PFD.cAlphaBits = 0;
PFD.cAccumAlphaBits = 0;
PFD.cAlphaShift = 0;
PFD.cBlueBits = 0;
PFD.cAccumBlueBits = 0;
PFD.cBlueShift = 0;
PFD.cGreenBits = 0;
PFD.cAccumGreenBits = 0;
PFD.cGreenShift = 0;
PFD.cRedBits = 0;
PFD.cAccumRedBits = 0;
PFD.cRedShift = 0;
hDeviceContext = GetDC(hWindow);
int pf = ChoosePixelFormat(hDeviceContext, &PFD); //throws error 1150, next three throw error 2000 because of this failing
SetPixelFormat(hDeviceContext, pf, &PFD);
hGLContext = wglCreateContext(hDeviceContext);
wglMakeCurrent(hDeviceContext, hGLContext);
if(GetLastError() != ERROR_SUCCESS)
{status = -1;}
else
{status = 0;}
return;}
Display::~Display()
{ wglMakeCurrent(NULL, NULL);
wglDeleteContext(hGLContext);
DestroyWindow(hWindow);
UnregisterClass(data.lpszClassName, data.hInstance);}
After I have tried all mentioned solutions I still had the same problem with ERR_OLD_WIN_VERSION after ChoosePixelFormat. In my case the problem was about the graphics card driver:
The system I'm working on uses an EVGA card with a GTX 770 GPU and yesterday I installed driver version 331.65. After that I got the same problems as the questioner. Installing the current Version 337.88 fixed the issue in my case. However ERR_OLD_WIN_VERSION seams to lead us in the wrong direction.
In your Display constructor, it looks like you don't initialize the hWindow member before you use it. That would be the value returned by CreateWindowEx.
Instead of testing the address of the GetLastError function, you should be calling it and testing its return value against ERROR_SUCCESS. I think this may be an oversight when you pasted the code, as you seem to be getting meaningful results from GetLastError (...).
UPDATE:
You might want to try something like:
#ifndef WINVER
# define WINVER 0x0500
#endif
Before #include <Windows.h>
That tells it to include all of the fields in the data structures that are new in Windows NT 5.0 (Windows 2000). Many of these structures determine the version of Windows they are targeting by the sizeof your structure, which will vary depending on how you have WINVER defined.
I was not able to boot up my older machine, but I did discover something when looking through the source code of SDL. It seems that they defined their own version of ChoosePixelFormat that loops through all available pixel formats using DescribePixelFormat and then compares them to the desired pixel format before choosing the best one. Since this is the exact same definition of windows's ChoosePixelFormat I suspect they had a good reason to make their own. Perhaps they knew it gave trouble in certain situations. Unfortunately since Microsoft Developer support is a myth, and barely anyone seems to care, this is as good an answer as I'll get for now. And since I've stopped caring too, this is probably the closest this question will ever get to an answer. Thnaks to those of you who tried to help.

Setting the Cursor Position in a Win32 Console Application

How can I set the cursor position in a Win32 Console application? Preferably, I would like to avoid making a handle and using the Windows Console Functions. (I spent all morning running down that dark alley; it creates more problems than it solves.) I seem to recall doing this relatively simply when I was in college using stdio, but I can't find any examples of how to do it now. Any thoughts or suggestions would be greatly appreciated. Thanks.
Additional Details
Here is what I am now trying to do:
COORD pos = {x, y};
HANDLE hConsole_c = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL );
char * str = "Some Text\r\n";
DWDORD len = strlen(str);
SetConsoleCursorPosition(hConsole_c, pos);
WriteConsole(hConsole_c, str, len, &dwBytesWritten, NULL);
CloseHandle(hConsole_c)
The text string str is never sent to the screen. Is there something else that I should be doing? Thanks.
Using the console functions, you'd use SetConsoleCursorPosition. Without them (or at least not using them directly), you could use something like gotoxy in the ncurses library.
Edit: a wrapper for it is pretty trivial:
// Untested, but simple enough it should at least be close to reality...
void gotoxy(int x, int y) {
COORD pos = {x, y};
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(output, pos);
}
See SetConsoleCursorPosition API
Edit:
Use WriteConsoleOutputCharacter() which takes the handle to your active buffer in console and also lets you set its position.
int x = 5; int y = 6;
COORD pos = {x, y};
HANDLE hConsole_c = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole_c);
char *str = "Some Text\r\n";
DWORD len = strlen(str);
DWORD dwBytesWritten = 0;
WriteConsoleOutputCharacter(hConsole_c, str, len, pos, &dwBytesWritten);
CloseHandle(hConsole_c);
Yeah, you forgot to call SetConsoleActiveScreenBuffer. What exactly was the point of creating your own? Use GetStdHandle(STD_OUTPUT_HANDLE) to get a handle to the existing console.
You were probably using ANSI excape code sequences, which do not work with Windows 32-bit console applications.
#include <windows.h>
#include <iostream.h>
using namespace std;
int main(int argc, char *argv[])
{
int x,y;
cin>>x>>y;
SetCursorPos(x,y); //set your co-ordinate
Sleep(500);
mouse_event(MOUSEEVENTF_LEFTDOWN,x,y,0,0); // moving cursor leftdown
mouse_event(MOUSEEVENTF_LEFTUP,x,y,0,0); // moving cursor leftup //for accessing your required co-ordinate
system("pause");
return EXIT_SUCCESS;
}