Is it possible to use C++ to simulate keypress? - c++

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

Related

Update getmaxyx() return values (ncurse / C++)

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);

Strange height value in the SDL_VIDEORESIZE event

I'm trying to create an application with the SDL, and would like the window to be resized.
For now, if I try to maximize the window, it works, if I place it in the left or right half of the screen, it works and take the right size.
But, when I resize the window by dragging one of it sides (vertical or horizontal), something really strange happen : the height grow until it's equal to the height of the screen.
When it grows, I can see that it's not instantaneous, in fact it takes many times times, growing each time of 37 pixels.
It's really strange, and I really don't know what to do.
I created a minimalist code to test if the problem was due to something special in my code, but it doesn't change anything, the problem is still the same.
Here is my minimalist code :
#include <SDL/SDL.h>
using namespace std;
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* surface=SDL_SetVideoMode(100, 100, 32, SDL_HWSURFACE|SDL_RESIZABLE);
SDL_Event event;
while (true)
{
SDL_Flip(surface);
SDL_PollEvent(&event);
if (event.type==SDL_QUIT) break;
else if (event.type==SDL_VIDEORESIZE)
{
surface=SDL_SetVideoMode(event.resize.w, event.resize.h, 32, SDL_HWSURFACE|SDL_RESIZABLE);
}
SDL_Delay(30);
}
}
So the problem don't seem to be in my code. (To verify that, I installed a game that use the SDL (Briquolo), and it has the same problem)
I searched on the web, but it seems that I'm the only person who got this problem (or it's maybe that I don't use the good keywords), so it seems that it's not the SDL.
The problem is probably caused by my system.
For information, got Ubuntu 16.10 64-bit, with the Gnome desktop.
How can I solve this problem, without having side effects ?
Finally found a way to avoid this (but I don't really understand why the first way didn't work) :
If I store the new sizes, process all events, and then resize, it works. Here's the working code :
#include <SDL/SDL.h>
#include <iostream>
using namespace std;
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* surface=SDL_SetVideoMode(100, 100, 32, SDL_HWSURFACE|SDL_RESIZABLE);
SDL_Event event;
bool resized=false;
int newW, newH;
while (true)
{
while (SDL_PollEvent(&event))
{
if (event.type==SDL_QUIT) return 0;
else if (event.type==SDL_VIDEORESIZE)
{
resized=true;
newW=event.resize.w;
newH=event.resize.h;
}
}
}
if (resized)
{
resized=false;
surface=SDL_SetVideoMode(newW, newH, 32, SDL_HWSURFACE|SDL_RESIZABLE);
}
SDL_Flip(surface);
}

If there isn't a keyboard input for a set amount of time skip needing input

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.

curses library: why does getch() clear my screen?

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..

How do I accept keyboard input in a live fashion?

I am currently writing a program in c++ that is very similar to the classic "snake" program with a few changes. I am writing it so that it will update the screen five times a second, based on ctime, possibly more if it can be handled. One thing that I would like to do is make it so that the program has a variable in the .h file "currkeypressed." This variable will hold the key that the user is currently holding down and the snake head will go in that direction. Each node in the snake will be a separate object so the currkeypressed will only affect the head. Directional and locational data will be passed down the snake from node to node at each update.
My question is: how can I get the program to keep this data constantly, rather than updating only with a cin when the key is pressed or at a certain interval? I know that I can accept the ascii value for the arrow keys in some sort of for loop, but that doesn't seem to work if the key is held down and if the loop is very long it can miss a press. Does anybody know how to do this?
EDIT: I am using a Linux OS, Ubuntu to be more precise
The simplest method is to use ncurse library.
However, if you prefer "raw" linux programming, you can use select and getchar:
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
fd_set readfs;
struct timeval timeout;
int res, key;
while (1) {
/* .. do something else .. */
FD_SET(0, &readfs); /* 0 is STDIN */
timeout.tv_usec = 10; /* milliseconds */
timeout.tv_sec = 0; /* seconds */
res = select(maxfd, &readfs, NULL, NULL, &timeout);
if (res) {
/* key pressed */
key = getchar();
if (key == 'A') { /* blar */ }
}
}
}
Once you are looking beyond simple line oriented or character orient input, you are into the details of the user input device. Each operating system has a particular mechanism for notifying a program of events like keydown and keyup.
To get an answer, add a tag for which programming environment you are in: MSWindows, Linux, Android, MacOS, etc.
You can use the library conio.h and you can use the function _getch() in a loop to get live input without any restriction.
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
char n='a';//Just for initialization
while(n!='e')
{
n=_getch();
}
return 0;
}
The simplest (although really not that simple) way would be to have a thread to capture the user input and then either have some kind of event driven system that can alert the head of the snake or the snake can poll for the current key.