C program to identify control or alt keypress - c

I am trying to write a C program which is aware of the control / alt / shift key being pressed down. I found something that provides this functionality in Java, but that's not helping me too much.
void CMousepresentView::OnDraw(CDC* pDC)
{
int shiftValue=::GetKeyState(VK_SHIFT);
if(!shiftValue)
pDC->TextOut(0,50,"Shift not pressed");
else
pDC->TextOut(0,50,"Shift pressed");
int ctrlValue=::GetKeyState(VK_CONTROL);
if(!ctrlValue)
pDC->TextOut(0,100,"Ctrl not pressed");
else
pDC->TextOut(0,100,"Ctrl pressed");
}
So what I have so far is quite rudimentary but I must start somewhere. It doesn't work though, at all.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
do {
ch = getchar();
putchar(ch);
} while(iscntrl(ch));
return 0;
}
I was hoping that iscntrl would at least give me some reaction from the system to start debugging and identifying the control sequence keypresses. No such luck.
If I could see an example that outputs "control is pressed / control is released", I could probably figure out the rest.
Update:
Have had some progress with this http://www.thelinuxdaily.com/2010/05/grab-raw-keyboard-input-from-event-device-node-devinputevent/
Update:
I think the answer is in using xlib. Thanks everyone.

You can not check for the silent keys in a console program, not just those keys. If using something like ncurses you might get them as modifiers on other keys.
If you want to make a program with a graphical user interface, it's not a problem. Qt is a popular framework for that. Check the documentation for the framework you select.

You may find the results of this question relevant, by using a raw keyboard mode.
Depending on the application, you may be able to use libSDL which has the ability to receive raw keyboard events.

Related

How to completely overwrite output in c

So I am working on this side project game kinda thing, and I want to put it inside of a border/box. I then want to print text constantly inside that border: adding text, removing it, changing it etc. I've looked far and wide, and cannot find anyway to print inside the box separately from the actual box.
My current implementation is to clear screen, and then reprint the entire box with new text using this:
printf("\e[1;1H\e[2J");
The issue with this is that I get this very obnoxious blinking effect, because every iteration of clearing my screen causes that portion of the screen to become black for a certain period of time.
So I am looking for a few solutions.
How to print a border separate from the print statement inside of it. I currently am implementing it like such:
printf("| | Hello There ||\n");
, and then repeating that all the way down to make a border.
How to completely overwrite the already outputted text so that this blinking effect can go away. So imagine \r removing a line, I want something like that, that removes the whole text and replaces it with a new set of text
How to change the location of where the user inputs into the console, so you can type into a box
Those are basically the only solutions I could think of, if you have any others I'd love to hear them
I also had a general question about c.
conio.h, graphics.h, windows.h and a few other headers don't work for my compilers. I use ubuntu, and they always come up with some error saying I can't use them. I appreciate someone explaining this to me.
Please let me know what you think, and if you need more info, I'll be sure to provide it
-Ryan
conio.h and windows.h are not standard Linux libraries, so they won't compile on Linux unless you install extra software. One solution would be to use a library designed for managing the screen like ncurses.
You can do that with loops and ASCII characters similar like that:
#include <stdio.h>
int main()
{
int i;
printf("\n\t\t═");
for(i=0;i<=20;i++)
{
printf("═");
}
for(i=0;i<=22;i++)
{
printf("\t\t║\n");
if(i==10)
{
printf("\t\t\tHello There \t\n");
}
printf("\t\t\t\t\t║\n");
}
printf("\t\t═");
for(i=0;i<=22;i++)
{
printf("═");
}
return 0;
}

How to fix movement in my snake program?

I'm programming now a snake program. I have a little problem in the movement. My direction buttons are the 'W' 'A' 'S' 'D' buttons.
I have a direction variable, wich type is char. I read a button from keyboard, direction gets a value, and the snake makes one step from the 4 directions, if I hit one from WASD and then enter. I'd like to fix the enter problem.
I want, that my snake moves continually, and doesn't wait for the enter.
I'd like to make a timer for direction that way, if I don't hit a character in X milliseconds, then the snake continues to move in the direction of the last value of direction.
How to make this timer? Or any other idea?
It depends on the language you are programming in :-).
Eg. if you have a sleep() or delay() function available, you don't need any special timers and a simple infinite loop will do the job.
The important thing is how you are reading the keyboard. You can read buttons as they are pressed (non-blocking) or waiting for them till they are pressed (blocking). In your case you are reading whole lines - this is why it waits for the enter.
Not sure what is your programming language, but this pseudo-code could explain it a bit. The keyPressed() and readKey() are some fictive library function, which you need to find in your language.
while (true) {
if (keyPressed()) {
direction = readKey();
}
move(direction);
sleep(1);
}
Unfortunately, without knowing the language and if an SDK like SDL, XNA, Monogame, etc. are used we can't help. I would suggest trying to search for handling keyboard events. In XNA while the game is running it calls Draw, Update, and Event. Usually the keyboard event would be handled like so:
//...
public void Update()
{
if(Keyboard.GetStates().IsKeyDown(Keys.W))
{
Player.ChangeDirection(Direction.UP);
}
//...
Player.Move();
}
Player.ChangeDirection(Direction) may will change how the snake moves. The movement is done in the Player.Move() command every time.
EDIT: In C++ are you using any SDKs like SDL, Allegro, DirectX or that?

how to get Return key press event?

I'm coding a console editor in C. I'm using CodeLite Editor on Windows. I want to insert a newline ('\n') when the user presses Return (Enter) key. I want to accomplish this goal with getchar() function is that possible?
I need it because I want to increment the y axis variable.
Code I'm trying on :
int X = 0; // X-axis
int Y = 0; // Y-axis
char key = getchar();
if (key=='sth') // Here I want to perform my check
{
//Do Something
++Y;
}
Update :
If it has a code like : '\x45' for example post it in the comments plz!!!
If you are trying to implement an editor, you will quickly find that getchar() is not the way to interpret keyboard events. In this very simplistic example, where all you might do is wait for a single keystroke of input that either is or is not a newline, your program will work if you change 'sth' (an abbreviation for "something"?) to '\n'. However, as your editor becomes more complicated, you will want to have an actual event handler that can detect any sort of keyboard events and can asynchronously deal with them. getchar() is not the way to do that.
This answer from 7 years ago shows that (1) you can go a limited distance with getch() (and getchar()), but (2) a far larger number of people agree that it's no substitute for a real event handler: Detect Keyboard Event in C

c/ncurses - using getch with different program sections

I am writing a simple ncurses program with a menu and different sections (create/view etc), all using the keyboard. Currently I have one getkey routine and then switches to determine which section the keyboard input is for, like this:
ch = getch();
if(menu){
switch(ch){
...
if(create){
switch(ch){
...
if(view){
switch(ch){
...
is this the best way to do this or should I have different getkey routines for each section (menu_getkey(), view_getkey() and so on) - what is the best way to do this?
This gets into a bit of design (and so might be a bit subjective), but I think your approach is fine. It allows you to handle common input logic close to the getch() before diving into specifics, and in general it's usually a good idea to handle events (e.g., keyboard input) in a single location if possible -- having multiple event loops tends to get messy as programs grow.
An equivalent way of writing it would be something like the following:
enum { MENU, CREATE, VIEW } input_focus = MENU;
...
void input_loop(void) {
for (;;) {
int ch = getch();
/* Put common input logic here. */
switch (input_focus) {
case MENU:
handle_menu_input(ch);
break;
case CREATE:
handle_create_input(ch);
break;
case VIEW:
handle_view_input(ch);
break;
}
}
}
Your individual cases might have to have some more logic in them, but you get the idea.
Having short functions helps with readability. Modern compilers are smart enough to inline functions that are only called once (remove the function call and insert the code directly instead), so don't worry about performance. (And in case someone nit-picky reads this -- yes, it would require link time optimization for functions in different compilation units.)
Having a function pointer that you update to always point to the current input focus instead of having the switch would be another option, but it's overkill here. It's ~kinda what C++ does for virtual functions.

keybord input using Winapi

I'm trying to make a simple text editor with winapi, its working for simple letter, but its not with capital letter or shift key.
char keys[256];
int x = 0;
while (1)
{
for (x = 0; x <= 256; x++)
{
if (GetAsyncKeyState(x) == -32767)
{
char c[5];
GetKeyboardState(keys);
ToAscii(x, MapVirtualKey(x, 0), keys, c, 0);
putchar(c[0]);
}
}
}
The behaviors of keyboard input are far more complex than what you think. Your method doesn't work because:
GetAsyncKeyState can miss keys. What happens when the user hits a key between calls?
What happens when you hold down a key? What about keyboard repeat?
Most critically, your code assumes a 1:1 relationship between key and character. You don't have any mechanism to deal with combinations like shift / caps lock state, or dead keys.
It would be better if you tried to explain what you're trying to do, and you can get advice on the right way to approach it. Trying to re-invent the behaviors of such a fundamental input device is not likely to be the best approach.
GetAsyncKeyState is likely not the way to go here: the real way to make a text editor type control is to instead handle the WM_KEYDOWN and WM_CHAR messages. Windows will send these to your WndProc when your HWND has focus. This is the technique used by the Windows EDIT and RichEdit controls.
Use WM_KEYDOWN to handle the non-character keys - like arrows (VK_LEFT, VK_RIGHT), page up and so on; and use WM_CHAR for text characters. WM_KEYDOWN tells you the key pressed using a VK_ value, and doesn't take shift state into account; while WM_CHAR does take shift state, so gives you 'A' vs 'a' or '1' vs '!' as appropriate. (Note that you have to have TranslateMessage in your messsage loop for this to happen.)
Having said all that, an even easier/better thing to do is just use the existing Windows EDIT or RichEdit controls and let them do the work for you - there's rarely a good reason to reinvent the wheel - unless you're playing around for fun and learning Win32 perhaps. Writing a proper text editor is pretty complex; there's a lot of non-obvious stuff to consider, especially when you get into non-English text: you'd need to ensure it works correctly with right-to-left text (Arabic, Hebrew), works with IMEs which are used to enter Japanese and Chinese characters. And you have to ensure that your control is accessible to screenreaders so that users with visual impairments can still use the control. EDIT and RichEdit do all this for you.
The actual Notepad app, for example, is just a wrapper for an EDIT control; while WordPad just wraps a RichEdit control; both let the control do all the hard work, and just add the extra UI and file save/load functionality on top.
Try to call
GetKeyState(VK_CAPITAL);
before
GetKeyboardState(keys);

Resources