Ask the C++ Pro 10-Minute Solutions

Detecting Keystrokes While Your Application is Busy: a 10-Minute Solution

Here's a question I get asked quite a bit. Windows uses a totally different model for detecting user input than what DOS programmers are accustomed to. Instead of having the application call the operating system to ask if the user has, for example, pressed a key, Windows calls the application when a user event has occurred. The application then does whatever it needs to and returns control back to the system.

Although this might seem a little upside-down at first, this approach is extremely flexible and works great. However, there are times when it is useful to be able to query the system for user events. For example, if your application is busy with a lengthy operation, it might be nice to detect if the user presses the Escape key as a way to cancel that operation. Fortunately, Windows allows you to do this.

When the user causes a system event by pressing a key or moving the mouse, the operating system stores these events in the appropriate application's message queue. These events are stored there as messages until the application returns control to Windows at which time Windows will send the next message from the queue to the application.

So, to find out if the user has pressed a particular key during a lengthy operation, your application needs to determine if a message for that key is currently in the application's message queue. You can determine this by calling the PeekMessage function as shown in this example.


MSG msg;

// Check for escape key
if (::PeekMessage(&msg, m_hWnd, WM_KEYFIRST,
                  WM_KEYLAST, PM_REMOVE)) {
   if (msg.message == WM_KEYDOWN && msg.wParam 
       == VK_ESCAPE)
      // Break out of your loop or
         otherwise stop working break;
}
The first argument to PeekMessage is a MSG structure that receives message information. The second argument is the handle of the window we are interested in. If you are using an MFC window-based class, you can just pass the m_hWnd member here. The next two arguments let us just look for certain types of messages. PeekMessage will return the first message in the queue that falls between these two values. Here, we were just interested in keystrokes so these arguments are set to WM_KEYFIRST and WM_KEYLAST. The last argument can be PM_NOREMOVE or PM_REMOVE and indicates if the message we get information about should be removed from the message queue. If the user pressed Escape, we don't want they keystroke going anywhere else, so we request that PeekMessage removes the message from the queue.

If PeekMessage finds a message within the request range, it returns a non-zero value. If this is the case, the code above checks to see if we found a WM_KEYDOWN message with wParam equal to VK_ESCAPE and, if so, breaks out of whatever the code is doing.

 
Other 10-Minute Solutions
 How to Change the Mouse Pointer without Flicker
 Setting Full Row Selection in ListView Control
 Automating Type Conversions with stringstream Objects
 Improving Memory Reallocation with Vectors
 How to Use <fstream> Classes for File I/O
 Casting About for Safe Typecasting
 Overloading Operator + the Right Way
 How to Create Persistent Objects
 Making Linked Lists More User-Friendly
 Preventing Glitches in Signal Processing
 Forcing Object Allocation on the Free-store
 Using String-Based Data Validation
 Implementing the 'Resource Acquisition Is Initialization' Idiom
 Simple Locks for Data Files
 Template Specializations
 Exception Handling
 Using Bit Fields in Data Optimization
 Using the Transform() Algorithm to Change a String's Case
 Use RTTI for Dynamic Type Identification
 Choosing the Right swap () Implementation
 Take Charge and Initialize Your Own Data
 Share Data Among Objects Using the Monostate Design Pattern
 String Manipulation Made Easy with std::string Algorithms
 Using typedef to Curb Miscreant Code
 Managing Objects' Construction Order
 Bitwise Operators: Combining Efficiency and Ease of Use
 Use Function Adapters to Extend Generic Algorithms' Usage
 Simplify Callback Dispatching with Enumerated Indexes
 Streamline Your Bulk I/O Operations with Stream Iterators
 Optimize Your Member Layout
 Preserve Code Safety with Conversion Operators
 Modify Your Base Class Interface in Derived Classes
 Tackle Common Programming Tasks Using the New <tuple> Library
 Use Local Classes for Proper Cleanup in Exception-enabled Apps
 Use multimap to Create Associative Containers with Duplicate Keys
 Enforcing Compile-time Constraints
 Facilitate Directory Operations with the <dirent.h> and <dir.h> Libraries
 Spruce Up Your Built-in Arrays
 Target 32- and 64-bit Platforms Together with a Few Simple Datatype Changes
 Restrict Object Allocation to Specific Memory Types
 Use the Pimpl Idiom to Reduce Compilation Time and Enhance Encapsulation
 Automate Resource Management with shared_ptr
 The Quick and Dirty Way to Add
 Pointing to Class Members
 Detecting Keystrokes While Your Application is Busy
 Linked Lists
 Programming the System Tray
 Create a "Universal" DLL
 Convert Path to Long Path Name
 Constructing an Object at a Pre-Determined Memory Position
 Declaring Classes and Member Functions in a Namespace
 Using the auto_ptr Class Template to Facilitate Dynamic Memory Management
 Using the random_shuffle() Algorithm to Randomize a Sequence of Elements
 Defining a Function Object
 Implementing the Singleton Design Pattern
 Declaring Function Pointers and Implementing Callbacks
 Overloading Operator << for a User-Defined Type
 Implementing a Stopwatch Class for Performance Measurements
 Creating and Accessing Environment Variables
 Executing an Object's Member Function in a Separate Thread
 Creating Heterogeneous Containers
 Overriding New and Delete
 Time and Date Manipulation
  Defining Functions with a Variable Argument List
 Optimize Abstract Operations with Function Templates




Sponsored Links


Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map
Jupiterweb networks

internet.comearthweb.comDevx.comClickZ

Search Jupiterweb:

Jupitermedia Corporation has four divisions:
JupiterWeb, JupiterResearch, JupiterEvents, and JupiterImages

Copyright 2004 Jupitermedia Corporation All Rights Reserved.
Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Jupitermedia Corporate Info | Newsletters | Tech Jobs | E-mail Offers