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
Related
I want to refresh the screen every one second. I'm implementing a chat with ncurses.
So far, I have the following function:
void print_chat(char *chat) {
mvprintw(1, 1, "RPC Chat");
move(2, 1);
for (int i=0; i<CHAT_WIDTH; i++) {
addch('_');
}
move(CHAT_HEIGHT + 3, 1);
for (int i=0; i<CHAT_WIDTH; i++) {
addch('_');
}
mvprintw(CHAT_HEIGHT + 5, 1, "Enter message: ");
}
Which prints the following screen:
In the main function I'd like to have a loop that refreshes the screen every 1 second, obtaining possible new messages from a server, and refreshes the screen in that interval so if any, new messages could be displayed. I also want to read users input while the refreshing goes on at the same time. Do I need threads?
My attempt so far in the main function:
while (1) {
print_chat(chat);
refresh();
sleep(1);
chat = read_chat_from_server();
/*char l = getch(); --> This would block the loop, waiting for input...
}
Do I need threads to achieve this? If so, would the thread be able to reprint the screen? Any other way to solve this problem?
The problem is that getch() is waiting for the user to press return.
You want to have a look at raw() and call it once before getting any input. By calling this function you can get characters from the user without him pressing return, pausing your program. Basically the console reads user input, prints each character as its being written, and when the user sends '\n', it returns that input to your program (See this answer).
You might want to look at noecho() too. Similar to raw(), lets you scan for user input (using getch()) without printing the characters on the screen. This is usually useful for letting your program handle how the characters are displayed.
Finally, it may be a good idea to call refresh() when something gets updated (e.g. check each second if you got a message, you sent one, etc.) and then call refresh(). If you still want to run it every second, maybe try nodelay(stdscr, 1), where stdscr is your default window:
The nodelay option causes getch to be a non-blocking call. If no input is ready, getch returns ERR. If disabled (bf is FALSE), getch waits until a key is pressed.
You need to call the timeout() function when you first initialize your program.
timeout(0) should cause getch() to not wait for user input.
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?
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);
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.
I have a small WIN32 C-Application in which i work with the KBDLLHOOKSTRUCT structure. This structure contains the VK-Code for a pressed key.
I try to convert this to an ASCII-Character. For this i use the Function MapVirtualKey, which works well.
The only problem is, that one VK-Code can stay for multiple chars.
Example:
On my keyboard (Swiss-German) exists the key-char .. If i press Shift+. then it creates a :. The VK-Code is the same. Thats no problem, and i can also check if Shift is pressed or Caps Lock is activated.
My only problem is: How can i get the char ':'?
I need a function like this:
GetKeyChar(vkCode, shift)
I need this to get the "normal" and the "shifted" value of the keyboard. Of course i could hardcode this, but i don't like to do it on this way.
The problem is that the KBDLLHOOKSTRUCT doesn't have all the information you need in order to do the translation. You get a message every time a key is pressed. So for Shift+X, you'll get an input message saying that the Shift key was pressed, and another message saying that the "X" key was pressed.
You need to call GetKeyboardState in order to get the state of the Shift, Alt, Ctrl, (and perhaps other) keys. Then call ToAsciiEx or ToUnicodeEx.
You're looking for ToUnicode, which returns the unicode character generated by that keypress.
The functions you are looking for are: ToAscii, ToAsciiEx, ToUnicode, ToUnicodeEx.
short VkKeyScan(char ch) API has contained the shift information. It translate char to virtual-key code and shift state.
See this: Convert character to the corresponding virtual-key code