📄 ncurses-programming-howto.html
字号:
then use htmldoc to get pdf file with htmldoc --size universal -t pdf --firstpage p1 -f <output file name.pdf> NCURSES-ONE-BIG-FILE.html for ps, you would use htmldoc --size universal -t ps --firstpage p1 -f <output file name.ps> NCURSES-ONE-BIG-FILE.html</font></pre></td></tr></table><p>See <a href="http://www.tldp.org/LDP/LDP-Author-Guide/" target="_top">LDP Author guide</a> for more details. If all else failes,mail me at <a href="ppadala@gmail.com" target="_top">ppadala@gmail.com</a></p></div></div><div class="SECT2"><hr><h3 class="SECT2"><a name="CREDITS" id="CREDITS">1.7.Credits</a></h3><p>I thank <a href="mailto:sharath_1@usa.net" target="_top">Sharath</a> and Emre Akbas for helping me with few sections.The introduction was initially written by sharath. I rewrote itwith few excerpts taken from his initial work. Emre helped inwriting printw and scanw sections.</p><p>Perl equivalents of the example programs are contributed by<a href="mailto:Aratnaweera@virtusa.com" target="_top">AnuradhaRatnaweera</a>.</p><p>Then comes <a href="mailto:parimi@ece.arizona.edu" target="_top">Ravi Parimi</a>, my dearest friend, who has been on thisproject before even one line was written. He constantly bombardedme with suggestions and patiently reviewed the whole text. He alsochecked each program on Linux and Solaris.</p></div><div class="SECT2"><hr><h3 class="SECT2"><a name="WISHLIST" id="WISHLIST">1.8. WishList</a></h3><p>This is the wish list, in the order of priority. If you have awish or you want to work on completing the wish, mail <a href="mailto:ppadala@gmail.com" target="_top">me</a>.</p><ul><li><p>Add examples to last parts of forms section.</p></li><li><p>Prepare a Demo showing all the programs and allow the user tobrowse through description of each program. Let the user compileand see the program in action. A dialog based interface ispreferred.</p></li><li><p>Add debug info. _tracef, _tracemouse stuff.</p></li><li><p>Accessing termcap, terminfo using functions provided by ncursespackage.</p></li><li><p>Working on two terminals simultaneously.</p></li><li><p>Add more stuff to miscellaneous section.</p></li></ul></div><div class="SECT2"><hr><h3 class="SECT2"><a name="COPYRIGHT" id="COPYRIGHT">1.9.Copyright</a></h3><p>Copyright © 2001 by Pradeep Padala.</p><p>Permission is hereby granted, free of charge, to any personobtaining a copy of this software and associated documentationfiles (the "Software"), to deal in the Software withoutrestriction, including without limitation the rights to use, copy,modify, merge, publish, distribute, distribute with modifications,sublicense, and/or sell copies of the Software, and to permitpersons to whom the Software is furnished to do so, subject to thefollowing conditions:</p><p>The above copyright notice and this permission notice shall beincluded in all copies or substantial portions of the Software.</p><p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ANDNONINFRINGEMENT. IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BELIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN ANACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.</p><p>Except as contained in this notice, the name(s) of the abovecopyright holders shall not be used in advertising or otherwise topromote the sale, use or other dealings in this Software withoutprior written authorization.</p></div></div><div class="SECT1"><hr><h2 class="SECT1"><a name="HELLOWORLD" id="HELLOWORLD">2. HelloWorld !!!</a></h2><p>Welcome to the world of curses. Before we plunge into thelibrary and look into its various features, let's write a simpleprogram and say hello to the world.</p><div class="SECT2"><hr><h3 class="SECT2"><a name="COMPILECURSES" id="COMPILECURSES">2.1.Compiling With the NCURSES Library</a></h3><p>To use ncurses library functions, you have to include ncurses.hin your programs. To link the program with ncurses the flag-lncurses should be added.</p><table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><pre class="PROGRAMLISTING"><font color="#000000"> #include <ncurses.h> . . . compile and link: gcc <program file> -lncurses</font></pre></td></tr></table><div class="EXAMPLE"><a name="BHW" id="BHW"></a><p><b>Example 1. The Hello World !!! Program</b></p><table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><pre class="PROGRAMLISTING"><font color="#000000"><span class="INLINEMEDIAOBJECT">#include <ncurses.h>int main(){ initscr(); /* Start curses mode */ printw("Hello World !!!"); /* Print Hello World */ refresh(); /* Print it on to the real screen */ getch(); /* Wait for user input */ endwin(); /* End curses mode */ return 0;}</span></font></pre></td></tr></table></div></div><div class="SECT2"><hr><h3 class="SECT2"><a name="DISSECTION" id="DISSECTION">2.2.Dissection</a></h3><p>The above program prints "Hello World !!!" to the screen andexits. This program shows how to initialize curses and do screenmanipulation and end curses mode. Let's dissect it line byline.</p><div class="SECT3"><hr><h4 class="SECT3"><a name="ABOUT-INITSCR" id="ABOUT-INITSCR">2.2.1.About initscr()</a></h4><p>The function initscr() initializes the terminal in curses mode.In some implementations, it clears the screen and presents a blankscreen. To do any screen manipulation using curses package this hasto be called first. This function initializes the curses system andallocates memory for our present window (called <var class="LITERAL">stdscr</var>) and some other data-structures. Underextreme cases this function might fail due to insufficient memoryto allocate memory for curses library's data structures.</p><p>After this is done, we can do a variety of initializations tocustomize our curses settings. These details will be explained<a href="#INIT">later</a> .</p></div><div class="SECT3"><hr><h4 class="SECT3"><a name="MYST-REFRESH" id="MYST-REFRESH">2.2.2.The mysterious refresh()</a></h4><p>The next line printw prints the string "Hello World !!!" on tothe screen. This function is analogous to normal printf in allrespects except that it prints the data on a window called stdscrat the current (y,x) co-ordinates. Since our present co-ordinatesare at 0,0 the string is printed at the left hand corner of thewindow.</p><p>This brings us to that mysterious refresh(). Well, when wecalled printw the data is actually written to an imaginary window,which is not updated on the screen yet. The job of printw is toupdate a few flags and data structures and write the data to abuffer corresponding to stdscr. In order to show it on the screen,we need to call refresh() and tell the curses system to dump thecontents on the screen.</p><p>The philosophy behind all this is to allow the programmer to domultiple updates on the imaginary screen or windows and do arefresh once all his screen update is done. refresh() checks thewindow and updates only the portion which has been changed. Thisimproves performance and offers greater flexibility too. But, it issometimes frustrating to beginners. A common mistake committed bybeginners is to forget to call refresh() after they did some updatethrough printw() class of functions. I still forget to add itsometimes :-)</p></div><div class="SECT3"><hr><h4 class="SECT3"><a name="ABOUT-ENDWIN" id="ABOUT-ENDWIN">2.2.3.About endwin()</a></h4><p>And finally don't forget to end the curses mode. Otherwise yourterminal might behave strangely after the program quits. endwin()frees the memory taken by curses sub-system and its data structuresand puts the terminal in normal mode. This function must be calledafter you are done with the curses mode.</p></div></div></div><div class="SECT1"><hr><h2 class="SECT1"><a name="GORY" id="GORY">3. The GoryDetails</a></h2><p>Now that we have seen how to write a simple curses program let'sget into the details. There are many functions that help customizewhat you see on screen and many features which can be put to fulluse.</p><p>Here we go...</p></div><div class="SECT1"><hr><h2 class="SECT1"><a name="INIT" id="INIT">4.Initialization</a></h2><p>We now know that to initialize curses system the functioninitscr() has to be called. There are functions which can be calledafter this initialization to customize our curses session. We mayask the curses system to set the terminal in raw mode or initializecolor or initialize the mouse etc.. Let's discuss some of thefunctions that are normally called immediately after initscr();</p><div class="SECT2"><hr><h3 class="SECT2"><a name="ABOUTINIT" id="ABOUTINIT">4.1.Initialization functions</a></h3></div><div class="SECT2"><hr><h3 class="SECT2"><a name="RAWCBREAK" id="RAWCBREAK">4.2. raw() andcbreak()</a></h3><p>Normally the terminal driver buffers the characters a user typesuntil a new line or carriage return is encountered. But mostprograms require that the characters be available as soon as theuser types them. The above two functions are used to disable linebuffering. The difference between these two functions is in the waycontrol characters like suspend (CTRL-Z), interrupt and quit(CTRL-C) are passed to the program. In the raw() mode thesecharacters are directly passed to the program without generating asignal. In the <var class="LITERAL">cbreak()</var> mode thesecontrol characters are interpreted as any other character by theterminal driver. I personally prefer to use raw() as I can exercisegreater control over what the user does.</p></div><div class="SECT2"><hr><h3 class="SECT2"><a name="ECHONOECHO" id="ECHONOECHO">4.3. echo()and noecho()</a></h3><p>These functions control the echoing of characters typed by theuser to the terminal. <var class="LITERAL">noecho()</var> switchesoff echoing. The reason you might want to do this is to gain morecontrol over echoing or to suppress unnecessary echoing whiletaking input from the user through the getch() etc. functions. Mostof the interactive programs call <var class="LITERAL">noecho()</var> at initialization and do the echoing ofcharacters in a controlled manner. It gives the programmer theflexibility of echoing characters at any place in the windowwithout updating current (y,x) co-ordinates.</p></div><div class="SECT2"><hr><h3 class="SECT2"><a name="KEYPAD" id="KEYPAD">4.4.keypad()</a></h3><p>This is my favorite initialization function. It enables thereading of function keys like F1, F2, arrow keys etc. Almost everyinteractive program enables this, as arrow keys are a major part ofany User Interface. Do <var class="LITERAL">keypad(stdscr,TRUE)</var> to enable this feature for the regular screen (stdscr).You will learn more about key management in later sections of thisdocument.</p></div><div class="SECT2"><hr><h3 class="SECT2"><a name="HALFDELAY" id="HALFDELAY">4.5.halfdelay()</a></h3><p>This function, though not used very often, is a useful one attimes. halfdelay()is called to enable the half-delay mode, which issimilar to the cbreak() mode in that characters typed areimmediately available to program. However, it waits for 'X' tenthsof a second for input and then returns ERR, if no input isavailable. 'X' is the timeout value passed to the functionhalfdelay(). This function is useful when you want to ask the userfor input, and if he doesn't respond with in certain time, we cando some thing else. One possible example is a timeout at thepassword prompt.</p></div><div class="SECT2"><hr><h3 class="SECT2"><a name="MISCINIT" id="MISCINIT">4.6.Miscellaneous Initialization functions</a></h3><p>There are few more functions which are called at initializationto customize curses behavior. They are not used as extensively asthose mentioned above. Some of them are explained whereappropriate.</p></div><div class="SECT2"><hr><h3 class="SECT2"><a name="INITEX" id="INITEX">4.7. AnExample</a></h3><p>Let's write a program which will clarify the usage of thesefunctions.</p><div class="EXAMPLE"><a name="BINFU" id="BINFU"></a><p><b>Example 2. Initialization Function Usage example</b></p><table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><pre class="PROGRAMLISTING"><font color="#000000"><span class="INLINEMEDIAOBJECT">#include <ncurses.h>int main(){ int ch; initscr(); /* Start curses mode */ raw(); /* Line buffering disabled */ keypad(stdscr, TRUE); /* We get F1, F2 etc.. */ noecho(); /* Don't echo() while we do getch */ printw("Type any character to see it in bold\n"); ch = getch(); /* If raw() hadn't been called * we have to press enter before it * gets to the program */ if(ch == KEY_F(1)) /* Without keypad enabled this will */ printw("F1 Key pressed");/* not get to us either */ /* Without noecho() some ugly escape * charachters might have been printed * on screen */ else { printw("The pressed key is "); attron(A_BOLD); printw("%c", ch); attroff(A_BOLD);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -