Linux c++ console get key state - c++

I want to create command line game in Linux but I don't know to get the key state. I heard of getch() but that stops the program.

I spent a little while reading around. Apparently, this is a hard thing to do without the help of a library. Many people recommended the library ncurses. If you want to try to do it by yourself, you need to learn about switching terminal modes and crazy stuff like that. This thread was very informative: Non-blocking keyboard read - C/C++

In this article, the author implements a cKeyboard class, which directly listens for events from /dev/event0. The class is then used as follows:
#include "keyboard.h"
cKeyboard kb;
...
if (kb.getKeyState(KEY_UP)) {
// do something
}
It works perfectly for me, but I had to change event0 to event4.

Related

Replacing std::cout output with windows form

I made a program in c++ (visual studio 2010) that looks for serial com ports and compares their friendly names with defined text. When there is a match that port is opened/connected and serial communication starts.
The program notifies the user when a com port is found, whether the connection was successful or not and if the data send was successful or not and other useful information. The program uses cout to notify the user.
I want to replace console output window with windows form but cant find much resources online on how to do this. To illustrate, I want this:
To become this:
I included form1.h and other files and tried replacing cout with below line but code is not compiling:
Form1::textBox1->Text = L" Text I want to display";
Can anyone explain how to use textBox1, or a tutorial for this?
"I included form1.h" - You can't just grab random files and hope it works. That is not how C++ works, or computers in general.
How then do you do something like this? The Standard Library provides std::cout and Visual Studio by default includes the Standard Library, so using it is fairly easy. But for graphics, you will need another library. I recommend Qt, if only because there are good tutorials for beginners.
So I finally did achieve the functionality I described above in my question and thought I should post my findings here.
To convert my code from console output to Windows Form I basically had to migrate from c++ to C++/cli.
holowczak.com has a great tutorial on how to get started with windows form (c++/cli) in visual studio.
Next if there is any busy looping(like infinite while-loop) in your c++ code then you would need to run that busy loop on a separate thread or the program can hang. Dr.Dobb's tutorial on how to create and mange threads in c++/cli, can help a lot.
Finally, if you need to access resources (such as textbox and other controls) of windows form from another thread then a thread-safe call has to be made. Microsoft's "HowTo:Make thread-safe call to windows Form controls" explains how the invoke method can be used for updating textbox from another thread.

Integrating C++ Code with a GUI

I am trying to implement a security system as part of my Microcontrollers term project. I am almost done with the software end of things. I just need to design a GUI that will serve as an indicator or an alarm device for my security system. The microcontroller makes use of the sensing circuitry to check if the system has been breached and it sends the alarm signal serially to a PC. I am reading data off the PC serial port using C++ and the whole thing works wonderfully. However, I am doing it in a console based environment. That's all I have ever known. I am studying to be an Electronic Engineer. :P
That's not acceptable, however, and I need to design a GUI for my project.
Question 1:
Is there anyway I can integrate my existing code with a GUI? I have googled this already without much luck. All the answers seem to point in the direction of external libraries like Qt etc. This is kind of scary because I don't have a lot of time.
Question 2:
As I mention earlier, I am kind of intimidated by the thought of having to use external libraries etc. so I tried to make a GUI on Visual Studio using Visual C++ based Windows Form Applications. I used the serialport utility from the Toolbox. I haven't been able to read data off the COM port that way but I can write data to it just fine.
This is what the form looks like:
I am trying to display the data read from the serial port on a textbox in response to a button press. Here's the code I am using for the button:
private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e)
{}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
this->serialPort1->PortName = "COM1";
this->serialPort1->Open();
this->serialPort1->BaudRate = 9600;
try
{
this->textBox1->Text=this->serialPort1->ReadLine();
}
catch(TimeoutException^)
{
this->textBox1->Text="Timeout Exception";
}
this->serialPort1->Close();
Can you tell me what I am doing wrong? I am new to this. This is my preferred method, btw.
Using Windows Forms is definitely the way to go if you don't want to use external libraries, that's how I'd have done it too.
I'm not exactly into these things, but using ReadLine() just once could be a possible source of the problem. Maybe the data coming in over the serial port is sent over more than just one line. Perhaps you'll have to loop through the input, continuously using ReadLine() and collecting the lines in an array until all data has been received.
But perhaps there's also another command, something like ReadAllLines(), which reads all the input at once and returns it to you?
My immediate suspicion is the ReadLine() command - are you sure your MC is writing the endline characters?
Use ReadFile instead and see if you can read single bytes. If not, then maybe you need to adjust more options. If you get to the timeout exception, then you will need to adjust the read timeout (SetCommTimeouts).
Everything you need was described very well by Allen Denver here: http://msdn.microsoft.com/en-us/library/ff802693.aspx
As for which GUI, if whatever Windows Forms project you're using works, then stick with it. I personally used MFC for a similar final year project, but that was because I was already familiar with it.
For next time though, learn C#. C# and Java are far, far easier and quicker for creating GUIs.
As for your question 1, I recommend you to use the MFC library, it is quite easy. Here is a good example for you to start.
http://depts.washington.edu/cmmr/biga/chapter_tutorials/1.C++_MFC_D3DOGL/1.StepByStepGuide/index.html
And based on what I understand, You are already able to read and write the data in console based environment. The GUI is just used to enter or display the data. In this case, you could program a MFC project easily which serves your purpose.
And for your 2nd question, if you tried to display the data read from the serial port on a edit box in response to a button press. You should first add a variable to the edit box, for example edit_box_value. And in that button clicked function, implement a code like following:
edit_box_value.Format(_T("%s"), data_to_be_displayed);
UpdateData(FALSE);

Get trigger from console in C++

I am writing an application for a robot.
The required UI for the application is described in the pseudo-code below:
while(true){
if (spacebar is not pressed){
//do something
}
else{
sleep(1); //wait for a second
}
}
If I use cin or some other console input reading function then it will wait for user to press something. How do I ensure that it does not wait to get any input?
I am using Ubuntu. But I do not want it to be OS-specific.
Answers here seem to be OS specific.
Terminal Level input
What you are asking for is fairly close to the hardware (key-press / key-release) compared to the "standard input/output" stream concepts. So your implementation would have to be OS specific. Having said that the library to use is curses[1] which has been around for a long time and is standard on a lot of Un*x platforms. The GNU ncurses flavor compiles for pretty much all of them, it is a standard install in almost all Linux environments, and where it isn't installed by default you can find it. It also works well in Windows (cygwin), os/2 and a bunch of embedded systems etc. so you should be able to write a fairly portable software using curses that does what you want.
It's not too clear what you're asking for. In the if, is the
condition based on whether a space character has been entered,
or whether the user is currently holding down the space bar? In
the first case, you need something like curses (a portable
library which does gets each character as it was entered,
without echo). In the second, I don't think that there is
a portable solution. Even non-portably, you might not be able
to get it if your program is reading from a terminal window
(e.g. xterm); this sort of information is typically only present
as window events, when you created the window in your program.

Multiple console windows from one Win32 console app

I've written a program based on an empty Win32 console app in VS2008 running on Win7 64bit. The program is entirely menu based spawning from a main.cpp which only calls external functions that lead to other interfaces based on the users needs (e.g. cashier, inventory, report, etc...). What I would love to do is provide a new console window for each interface.
Ideally it would close the main menu upon invoking any other interfaces and so on as the user progresses through its functions, including reopening the main menu when necessary.
The basis for doing it this way is that I'm starting a new semester next week diving deeper in OOP with C++ and I wanted to go over my text and complete the capstone project which progresses with the topics to ensure that I have all the basics down pat. As much as I would love to do this the smartest-easiest way, it's best if I stick to the limited knowledge presented in the book which only hints at STL and speaks nothing of additional libraries like boost.
I, of course, have searched on SO and elsewhere looking for the solution. I have found answers, most of them falling outside of my tight requirements, some dealing with building a console window from scratch. While from-scratch seems the most promising, it seemed to be dealing with those not using a robust IDE like VS and I don't know if it will cause more conflict than it's worth, or if it can even be used in multiplicity. The majority, however, left me with the impression it isn't possible. The one exception to this was linking a console to a process. This is what I hope is in my future!
What brought me to this was the need to present a clean look at each turn of events. At first I was fooling around with trying to clear the screen with a basic function like void clearScreen(int lines); but this will always clear from the bottom. So, if I clear the screen before the next interface it's still at the bottom. If I clear it then accept input, the prompt is still at the bottom.
In case it hasn't been clear up to this point. My question is:
Is it possible, within reason, to produce multiple console windows which are tied to processes, or is there an easy way which I do not know to manipulate the scrolling of the main console window?
Even though I "need" to stay within the confines of the baby-step process of traditional learning, I would love to hear any input aside from switching the app type.
This is more of an OCD issue than a requirement of the task, so if the effort isn't worth the benefit that's okay too.
There is no portable way of moving the cursor around the console window - in Unix/Linux, you can send terminal codes for that, in Windows I have no idea.
What would work cross-platform, but be terribly slow and not too nice, would be:
read your input character-by-character
remember where on the screen the next character should appear
redraw the whole screen after each key press
If you want to do better, you must turn to platform-specific solutions, or find a library which would do it for you (like ncurses in the Unix world), but I don't know if any of these fit in your requirements.
You can set the cursor-position on Windows using SetConsoleCursorPosition.
Since you were saying something about VS, I assume restricting yourself to Windows isn't a problem. If so, you can use the Windows API for this.
Other than that, ncurses seems to be at least partially ported to most common platforms.
If you were looking for a way to do this in standard C++ - it doesn't exist. C++ doesn't require the platform it's running on to even have a console, so there are no console manipulation functions.
Both aren't that hard to use, but if this is really just some student thingy where you expect to learn something useful you probably shouldn't bother. Console manipulation isn't something you'll have or want to do very often.
Although it may not have been clear in my original question, I was looking for a solution to be used in a console window. Ideally the solution would have been operable on at least Linux and Windows because any programs I write for school must be compiled on each. This wasn't an assignment but it's obviously advantageous to learn things that are usable there as well.
Here's what I found ...Solution thanks to Tim Wei
void clearScreen()
{
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
This, as simple as it is, was exactly what I was looking for. The function clears the screen and puts the cursor at the top of the console window providing a way to provide static headers or titles with changing data tables. It also allows for simple text based animations - if you like that sort of thing. It made a significant difference in the look, feel and consistency in my console applications this semester!

Clear console using C++ with Xcode?

I'm trying to make a C++ console application using Xcode 4.1, but I can't find the command for cleaning the screen while the program is executing...
Any ideas? Thanks!
OSX doesn't have "consoles" the way Windows does. It has pseudoterminals, which act like an old-fashioned glass terminal to the program running "inside" them, and like a bidirectional pipe to the program that set them up. That outer program can do whatever it likes with the inner program's input and output. Notable examples of such programs are Terminal.app, which emulates the venerable VT-100, and ssh, which forwards the I/O over a secure channel to its own controlling terminal (which is probably itself a pseudoterminal). This is all by way of saying that there isn't a method that's guaranteed to work, because maybe the program on the outside of the pseudoterminal doesn't have a "screen" that you can meaningfully "clear." (Expect is a good example of a program like that.)
Having said that, though, if there is a screen, these days you can pretty much count on it to respect the VT-100 control codes. So this should do what you want:
std::cout << "\033[2J" << std::flush;
If you find that you need even one more control code, though, it's time to hook your program up to ncurses, which presents a nice friendly API to all the tricks that modern terminal windows are capable of, and will also have your back in the increasingly unlikely event that your program is attached to a terminal (or a program emulating a terminal) that is not a VT-100 nor one of its descendants.