I'm trying to learn the curses library (pdcurses, as I'm in Windows OS), with C++.
I have a program that displays 3 windows, then a while loop to do some processing based in key presses captured by getch(). The loop gets exited when the F1 key is pressed.
However, despite refreshing all three windows with wrefresh(), nothing appears before I enter my first key press. Without the while loop, everything is displayed fine. I've made numerous tests and it's like the first call to getch() will completely clear the screen, but not the subsequent ones.
My question is: what did I miss? At first, I was thinking that maybe getch() was calling an implicit refresh(), but then why do subsequent calls to it not have the same behaviour?
Thank you very much in advance for your help.
Here is the code.
#include <curses.h>
int main()
{
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
curs_set(0);
WINDOW *wmap, *wlog, *wlegend;
int pressed_key;
int map_cursor_y = 10, map_cursor_x = 32;
wlog = newwin(5, 65, 0, 15);
wlegend = newwin(25, 15, 0, 0);
wmap = newwin(20, 65, 5, 15);
box(wmap, 0 , 0);
box(wlog, 0 , 0);
box(wlegend, 0 , 0);
mvwprintw(wlog, 1, 1, "this is the log window");
mvwprintw(wlegend, 1, 1, "legends");
mvwaddch(wmap, map_cursor_y, map_cursor_x, '#');
wrefresh(wlog);
wrefresh(wmap);
wrefresh(wlegend);
while ((pressed_key = getch()) != KEY_F(1))
{
/* process keys to move the # cursor (left out because irrelevant) */
box(wmap, 0 , 0);
box(wlog, 0 , 0);
box(wlegend, 0 , 0);
wrefresh(wmap);
wrefresh(wlog);
wrefresh(wlegend);
}
endwin();
return 0;
}
Your first instinct was correct: getch() does an implicit refresh(). Specifically, getch() is equivalent to wgetch(stdscr), so it's an implicit wrefresh(stdscr) -- updating a window (stdscr) that you're not otherwise using, that just happens to fill the screen. The reason that subsequent calls have no effect from that point on, is that stdscr is already up to date, as far as curses is concerned, since you never write to it after that (never mind that its contents have been overwritten on the actual screen).
The solution is either to call refresh() explicitly at the top, before you begin drawing; or, my preference, to call wgetch() on a different window (whichever is most appropriate), instead of getch(), and ignore the existence of stdscr entirely. Just remember that all the functions that don't let you specify a window -- getch(), refresh(), etc. -- are really calls to their "w" equivalents, with stdscr as the implicit window parameter.
By default getch() blocks until a key is pressed. Change your loop to be a do {} while(); loop:
pressed_key = /* some value that will be benign or indicate that nothing has been pressed */
do {
/* process keys to move the # cursor (left out because irrelevant) */
box(wmap, 0 , 0);
box(wlog, 0 , 0);
box(wlegend, 0 , 0);
wrefresh(wmap);
wrefresh(wlog);
wrefresh(wlegend);
} while ((pressed_key = getch()) != KEY_F(1));
If you need getch() to be non-blocking, the way to do that is to set curses for nodelay mode on the default window.
From the pdcurses docs:
With the getch(), wgetch(), mvgetch(), and mvwgetch()
functions, a character is read from the terminal associated with the
window. In nodelay mode, if there is no input waiting, the value ERR
is returned. In delay mode, the program will hang until the system
passes text through to the program.
So call:
nodelay(stdscr, TRUE);
if you want getch() to be non-blocking; it will return ERR if no key has been pressed.
getch() doesn't clears your screen, it just does what it was made to do, blocking your while loop, waiting to get a character from your keyboard.
So here's something that could fix your problem. Before curses.h, include conio.h, and make your while loop like this:
do
{
box(wmap, 0 , 0);
box(wlog, 0 , 0);
box(wlegend, 0 , 0);
wrefresh(wmap);
wrefresh(wlog);
wrefresh(wlegend);
if(kbhit())
pressed_key = getch();
}while (pressed_key != KEY_F(1));
Here's another fix for you, that will also make #Kaz happy. This time we'll use windows.h instead of conio.h, and you don't need that pressed_key anymore. Make your while loop like this:
do
{
/* process keys to move the # cursor (left out because irrelevant) */
box(wmap, 0 , 0);
box(wlog, 0 , 0);
box(wlegend, 0 , 0);
wrefresh(wmap);
wrefresh(wlog);
wrefresh(wlegend);
}
while (!GetAsyncKeyState(VK_F1));
By the way using nodelay, as suggested in another answer will fix the current problem, but it will pretty much make the use of curses.h "useless", except for the fact you can still do some quick graphics in the console, that can be made with a bit of skill without the use of any library. You'll see what I mean if you'll make a little animation in that menu, like a moving cursor driven by your keyboard and so on. Basically curses are mostly used just because of its delaying capabilities, making things look more natural in the console, so they won't flicker, especially when it comes to details / animations generated through repetitive loops..
Related
Is it possible to use C++ to simulate keypress? What I mean by that I mean is it possible to use C++ to emulate your keyboard to type out a word. If you are still confused about what I am talking about (Like the rest of the internet) then what I am trying to say is if there is a way to copy something like pyautogui and pynput in C++. I've looked everywhere for an answer but all I saw was key detection. I want to know how to do this because my friends keep spamming me so I want to get my revenge by making a spam bot. Here's the code so far..
#include <iostream>
#include <windows.h>
using namespace std;
string message = "Lol";
float delay = 0.2f;
void click_to_location()
{
Sleep(5000);
SetCursorPos(525, 665);
Sleep(10);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
Sleep(10);
}
int main()
{
while (true)
{
if (GetAsyncKeyState(0x51))
{
exit(0);
}
// Help with key Press here
Sleep(10);
// Help with key Release here
}
return 0;
}
Also ignore my bad programming skills.
From my experience, simulate keystroke is not language specific.
Can simulate keystroke on windows using win32 api and c++. https://learn.microsoft.com/en-us/windows/win32/learnwin32/keyboard-input
So, I'm, trying to be able to correctly resize my console window using ncurse in C++. I've been able to catch when the window is resize, the problem is that I'm not 100% sure how should I proceed after that. Let's say I have this loop in my main function (after initializing ncurse and those things...):
while(ch = getch())
{
if(ch == KEY_RESIZE)
{
DoSometing();
}
}
As I said the DoSomething in that example is called. But if I try to use ncurse's functions to get the new size of the window with
getmaxyx(stdscr, yMax, xMax);
I'm get the same values (the initial values) over and over again. I guess that's because when I do initscr(), the window size is stored somewhere and that's the value that the getmaxyx function provides. I've tried to do something like call endwin() and the again initscr() to restore those values, but that doesn't seem to work, the value that getmaxyx returns is fixed.
After searching for alternative solutions, I kind of solve the problem, using some other libraries. That's an small example, which actually works as I wanted:
#include <cstdlib>
#include <ncurses.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
initscr();
noecho();
box(stdscr, 0, 0);
struct winsize w;
int ch, x, y;
while(ch = getch())
{
if(ch == KEY_RESIZE)
{
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
resize_term(w.ws_row, w.ws_col);
clear();
box(stdscr, 0, 0);
}
refresh();
}
}
The thing is I'm kind of worried about portability while using this new libraries (I'm not completely sure, because I haven't started testing yet, but I understand that ncurse programs can be port to Windows).
I would really appreciate any information about how to do this in ncurse without using any other library (if it's possible), if what I'm doing now is OK or if I should be doing it in any other way. Any hint in the right direction is what I'm looking for :)
I'm using Arch Linux (kind of noobie) and qtile as a window manager. If you need any other relevant information, just ask me. Thanks for the help!
This is causing the example to produce bogus results:
if(ch = KEY_RESIZE)
since it is always true (not a comparison, but an assignment). The "something" is not doing anything useful, because the condition is incorrect.
Change that to
if(ch == KEY_RESIZE)
and get rid of
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
resize_term(w.ws_row, w.ws_col);
int main()
{
while (true)
{
if (GetAsyncKeyState(VK_LBUTTON))
{
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
}
}
The problem with this code is: It keeps clicking, so the program continues, and it doesn't stop clicking. I was wondering why and how to fix it.
Use
if ((GetAsyncKeyState(key) & 0x8000) != 0)
From https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getasynckeystate:
Although the least significant bit of the return value indicates whether the key has been pressed since the last query, due to the pre-emptive multitasking nature of Windows, another application can call GetAsyncKeyState and receive the "recently pressed" bit instead of your application. The behavior of the least significant bit of the return value is retained strictly for compatibility with 16-bit Windows applications (which are non-preemptive) and should not be relied upon.
I am trying to get a keyboard input, but if it doesn't happen in about half a second I want it to continue to the rest of the loop. I tried using kbhit(); but it won't wait for the input, it just loops with out stopping. This is the loop in question:
while(flags)
{
gameing.updateDraw(0, 0);
keyIn = getch();
//Sleep(20);
switch(keyIn)
{
case UP_ARROW:
flags = gameing.updateDraw(-1, 1);
break;
case DOWN_ARROW:
flags = gameing.updateDraw(1, 1);
break;
case WKEY:
flags = gameing.updateDraw(-1, 2);
break;
case SKEY:
flags = gameing.updateDraw(1, 2);
break;
}
All help will be greatly appreciated. I am trying to avoid using alarm();
The comnented call to Sleep indicates that this is a Windows program using <conio.h> functionality, and not a *nix program using curses.
With <conio.h> you can use the kbhit function to check whether there is a keypress.
Place that in a loop that sleeps a little bit between each call.
More advanced you can use the Windows API. Its wait functions can wait on a console handle, with a specified timeout.
The C++ standard library does not have unbuffered keyboard input functionality.
Try using something like ctime.h or chrono to get the time difference. Then do something like
long lastTime=CurrentTime();
int input=0;
while(!(input=kbhit()) && CurrentTime()-lastTime < 20);
if(input)
// do stuff with input
// do all the other stuff
lastTime=CurrentTime();
Disclaimer. I'm not particularly familiar with kbhit and things, but based on a little bit of googling, this seems like it ought to work. Also the implementation of CurrentTime is up to you, it doesn't have to be a long or anything, I just chose that for simplicity's sake.
I am having a hard time trying to get wgetch to read data from a window after moving and resizing it.
Upon input, I move the window up and increase it's height by 1 too. I then clear the window and write data back to it. The problem is when I do wgetch (or mvwgetch) it positions the input cursor at the previous position before I moved the window up.
Here's my code:
#include <ncurses.h>
int main() {
WINDOW *win=initscr();
int y,x,i=1;
getmaxyx(win, y, x);
//creates a sub windows 1 col high
WINDOW *child=derwin(win, i, x, y-i, 0);
//doc says to touch before refresh
touchwin(win);
//print to child
waddstr(child, "hello");
wrefresh(child);
wrefresh(win);
noecho();
while(wgetch(child)!='q') {
++i;
mvderwin(child, y-i, 0);
wresize(child, i, x);
touchwin(win);
wclear(child);
waddstr(child,"hello");
wrefresh(child);
wrefresh(win);
}
delwin(child);
delwin(win);
endwin();
}
Here the word "hello" does move up as expected, however, the input cursor is in the wrong place. Using mvwgetch still causes the same problem. cbreak(), noecho() and scrollok(child) also don't seem to be helping.
Thanks
EDIT: updated version better displaying the problem http://liveworkspace.org/code/31DruQ$0
You have to catch SIGWINCH, that signal is sent when you resize the terminal. Do an endwin(), a refresh(), and then repaint your windows. Cursor position is relative to the windows, not the actual terminal size. The windows are not resized automatically.
Edit: Right, you're actually resizing the windows, not the terminal. In that case, first of all, do a wrefresh on the child LAST, the cursor shown on the screen is the one of the refresh that happened last.
Put a box around your subwindows and check that they're actually getting resized / moved properly.