Processing Keyboard Messages

Environment: Windows and MFC

Most of the material in this article discusses the processing of keyboard messages in dialogs and MFC form views. Much of this also applies to other types of windows. Topics covered are:

  • A summary of dialogs, controls, and keyboard messages
  • The WM_GETDLGCODE Message for processing most any key typed in a control
  • Using Accelerator Keys to process most any key (combination) for an entire dialog
  • An alternative solution for disabling the Enter and/or Escape key(s)
  • Short comments about PreTranslateMessage

There are many more good solutions for processing keys and overriding how keys are processed. It is difficult to decide which other ones are worth mentioning. Therefore, the solutions described here are limited to ones documented in the MSDN (in fact, they are either in the Microsoft Knowledge Base or the Microsoft Systems Journal).

Summary of Dialogs, Controls, and Keyboard Messages

Windows programmers, especially beginners, often want to process keyboard messages for an entire dialog instead of for individual controls in the dialog. Another behavior that is often overridden is the behavior of the Enter and/or Escape keys specifically.

Windows does not provide a direct solution for processing keyboard messages for an entire dialog because that is inconsistent with the design of dialog boxes. Normally, there will always be a control in a dialog that has the focus. The only way I know of to have a dialog without any control having the focus is to have no control (enabled) in the dialog. The normal method of processing keyboard messages in a dialog is for the messages to always be processed by a control that has the focus in the dialog. Therefore, in a dialog (or form view), whenever possible, process all keyboard messages in a control. In other words, have a control, such as an edit control, in the dialog that usually has the focus and processes all keyboard messages in that control.

When a control has the focus, it receives messages for keys entered by the keyboard. The type of control and the styles set for it determine what keys are sent for us to process. For some controls, such as the edit control, there are styles that affect what keys are sent by the default processing. In most cases, it is just the Return (Enter) key that is affected. For example, for multi-line edit controls, the Enter key can be sent but only if the edit control is a multi-line edit control and if the "Want Return" style is set. Which keys are sent or are not sent by default can be overridden however by processing theWM_GETDLGCODE message, described below.

The Enter and Escape keys are a bit of an exception. Unless the Enter key is processed by a control, it will have the effect of the default (usually "OK") button for the dialog being pressed. The Escape key will generate the IDCANCEL command. Often, Windows programmers do not like that behavior. Beginner Windows programmers need to understand that this is standard behavior and therefore it is not necessary to change it. When this behavior is to be overridden, the easiest and most practical solution is to make the Enter and/or Escape key(s) accelerator key(s). There is an explanation and sample code for doing this below. Also see the topic "Dialog Box Keyboard Interface" in the "Dialog Box Programming Considerations" article of the Windows SDK documentation; the online copy is at Dialog Box Programming Considerations.

Most any key can be used as an accelerator key and therefore most any key can be overridden for an entire dialog. The disadvantage of using accelerator keys is that a multi-line edit control will not receive the Enter key unless additional code is used; however, the alternative described in "Disabling Enter and/or Escape Key(s)" below can be used instead for disabling the Enter key from closing the dialog.

The WM_GETDLGCODE Message

You can process WM_GETDLGCODE in a class derived from an MFC control class, such as CButton and CEdit. In your message handler, return DLGC_WANTMESSAGE or DLGC_WANTALLKEYS instead of, or in addition to, the return value of the base class OnGetDlgCode. Then, your keyboard message handlers will receive messages for more of the keys than it would by default. The following are two possible samples:

UINT CButtonx::OnGetDlgCode() {return 
     CButton::OnGetDlgCode()| DLGC_WANTMESSAGE;
}
UINT CButtonx::OnGetDlgCode() {
return DLGC_WANTALLKEYS;
}

Then, if you process the WM_CHAR message, your OnChar function will get more keys than if you did not override OnGetDlgCode. The Enter ("Return") key is one that will be received that might not be received without the OnGetDlgCode override. When the Enter ("Return") key is pressed, the nChar parameter of OnChar will be '\r' and for the WM_KEYDOWN and WM_KEYUP messages, nChar will be VK_RETURN. The NM_RETURN notification message also might not be sent without the WM_GETDLGCODE message being processed to request that the Enter key be sent.

Using Accelerator Keys

Dialogs do not process accelerator tables, but support of them can easily be added. The following describes how to revise your MFC CDialog-derived class to process an accelerator table for a dialog. Code must be added to CDialog::OnInitDialog to load the accelerator table and CDialog::PreTranslateMessage must be overridden to process accelerator keys.

If OnInitDialog for the dialog has not yet been overridden, use ClassWizard to add an override for it. Then, after the call to the base class OnInitDialog, add:

m_hAccel = ::LoadAccelerators(AfxGetResourceHandle(),
             m_lpszTemplateName);
if (!m_hAccel)
  MessageBox("The accelerator table was not loaded");

Note that m_lpszTemplateName is a protected and therefore undocumented member of CDialog and CFormView, but it can be used in classes derived from them. It points to the name or MAKEINTRESOURCE value for the dialog. That value can be used as shown if you copy the dialog's id from its properties to the id for the accelerator table. Alternatively, you can use something such as:

m_hAccel = ::LoadAccelerators(AfxGetResourceHandle(),
             MAKEINTRESOURCE(IDR_ACCELERATOR1);

Then, in the dialog's header, add:

HACCEL m_hAccel; // accelerator table

Then, use ClassWizard to add an override for PreTranslateMessage. Add the following to it:

if (WM_KEYFIRST <= pMsg->message && pMsg->message
                <= WM_KEYLAST)
  if (m_hAccel && ::TranslateAccelerator
     (m_hWnd, m_hAccel, pMsg))
    return TRUE;

You now have a dialog class that processes accelerator keys.

The next thing to do is to create an accelerator table resource. The resource id of the accelerator table resource must be the same id specified in the LoadAccelerators function; if you use the m_lpszTemplateName member variable, the accelerator table resource id must also be the same as the dialog resource id.

Entries in the accelerator table specify a key (combination) and a corresponding command id.

After creating the accelerator table, use ClassWizard to add a handler for the id(s) you provided in the accelerator table. Then, you can do most anything in the handler that you need to do when the key is typed. If you do nothing in the handler, nothing happens when that key (combination) is typed. Assuming that it is the Enter key that was entered into the table, pressing the Enter key would do nothing.

The following code can be used to simulate the tab key. This is most often used in a handler for the Enter key.

CWnd* pWndNext = GetNextDlgTabItem(GetFocus());
if (pWndNext)
  GotoDlgCtrl(pWndNext);

In C++ Q&A: Enabling Menus in MFC Apps, Changing the Behavior of Enter with DLGKEYS Sample App (the second question), the sample uses "pWndNext->SetFocus();" instead of "GotoDlgCtrl(pWndNext);" but in the second portion of the MSJ C++ Q&A for July 1997 article, Paul DiLascia explains why it is better to use GotoDlgCtrl.

Disabling the Enter and/or Escape Key(s)

The Enter and/or Escape Key(s) can be disabled by making the resource id for the Okay and/or Cancel buttons, not IDOK or IDCANCEL (correspondingly). See the Microsoft Knowledge Base Article Q122489 ("How to Disable Default Pushbutton Handling for MFC Dialog") for the KB article describing this solution. The advantage of this solution for disabling the Enter key from closing the dialog compared to using an accelerator key is that a multi-line edit control will continue to work as it should without requiring other modification.

The following is the essential part of it. I am assuming that a handler for the Okay and/or Cancel buttons has not yet been created. If it has (they have), you can adjust the following correspondingly.

  • Use the ClassWizard to create a handler for the Okay and/or Cancel button. When creating the handler, the object will be IDOK (for disabling the Enter key) or IDCANCEL (for disabling the Escape key). Choose the BN_CLICKED message.
  • Then, use the resource editor to modify the dialog by changing the resource id for the Okay and/or Cancel button(s) to something else. For the Okay button, uncheck the checkbox for the Default Button property.
  • Use ClassWizard again to create a handler for the button(s) with the new resource id. That is, the object will be the new resource id assigned to the button.
  • Finally, move the call to the base class function (CDialog::OnOk or CDialog::OnCancel) from the OnOk or OnCancel function to the new handler function. The name of the new handler function(s) depends on the resource id you gave to the Okay and/or Cancel button.

Notice that if the focus is on either of the buttons modified as above, pressing Enter will send the command (the button will work). If the focus is not on either of the buttons modified, entering the corresponding key (Enter and/or Escape) will not cause the command to be sent; in other words, the key is disabled.

If the Escape key is disabled in this manner, the Close system command (including the "X" at the top right) does not work. This can be fixed simply by using the ClassWizard again to create a handler for the WM_CLOSE message. In the generated handler, change:

CDialog::OnClose();

to:

CDialog::OnCancel();.

PreTranslateMessage

There are a few MFC programmers who prefer using PreTranslateMessage to process keys for a dialog or for controls in a dialog. PreTranslateMessage is an MFC function that processes accelerator keys (as in the sample above) and tooltips but is not intended to process keyboard messages for the other purposes the above solutions do. By using the WM_GETDLGCODE message solution, it is possible to use Windows and MFC to write functions that are specific to each control and that is for a specific message sent to the control. By using the accelerator table solution, it is possible to write a function specific to each key (combination) in the accelerator table, whereas the PreTranslateMessage function processes all messages for all controls. It can of course dispatch combinations of messages and controls to other functions, but why not use MFC as shown above to do that?

References

The following articles are directly relevant to the solutions provided above.

The following articles provide other possible solutions:

Downloads

None

IT Offers

Comments

  • シャネル マトラッセ バッグ

    Posted by Viorryign on 05/07/2013 09:26am

    [url=http://www.tiffanyjewelleryonlinestore.com/ティファニーリング-セール-6.html ]ティファニー バイザヤード ブレスレット [/url] genALY[url=http://www.pandoradiscountonlineshop.com/ ]パンドラ アクセサリー [/url] OnelfhelpDefs OnelfhelpDefsgennickR gennA]LY[url=http://www.tiffanycharmscheaponlineshop.com/index.php?main_page=faq ]ティファニー ブレスレット [/url] OnelfhelpDefsgennickQ gennicG[url=http://www.discountchristianlouboutinsalejp.com/specials.html ]クリスチャンルブタン サンダル [/url] OnelfhelpDefsgennickG gennickG[url=http://www.mcmbagscheapsaleonline.com/ ]エムシーエム バッグ [/url] OnelfhelpDefs OnelfhelpDefsgennickR gennickL[url=http://www.mcmbagsonlinestorejp.com/ ]エムシ-エム キーケース [/url] tgennickA

    Reply
  • Isabel Marant Boots

    Posted by CrengarnexSap on 03/28/2013 01:30pm

    Hong Kong Celebrities in [url=http://austinandrew.co.uk/General/isabelmarant.aspx]Isabel Marant Sneaker Wedges sale[/url] Spotted – Kelly Chen, Florinda Ho and Hillary Tsui looking onto in Isabel Marant pieces from the Spring/Summer 2012 collection. We also spotted Joey Yung at the rave IT threw since Isabel while she was in community at Zuma matrix week. Isabel Marant Opens Third Hong Kong Shop on Ice Dwelling Byway someone's cup of tea, Coming to Burgh on May 19 Assume from on how YOU can take first prize in a odds to rally Isabel in Hong Kong! The modish, and third in Hong Kong, Isabel Marant store on Ice Dwelling-place Drive in Main covers an limit of 570sq.ft. with the décor being a collaboration between Isabel Marant and the French construction firm ciguë. To revel the grand rift of the contemporary Ice Building Street accumulate, the set from France has particularly designed a pair of Asian limited version morose tie-dye sneakers, merely available at Isabel Marant Paris, Hong Kong and Beijing. Mind our gallery of the remodelled cumulate here and how you can connect us at an exclusive cocktail welcome for Isabel at Zuma on May 19. And we’re same excited to forth a setting as undivided of our Butterboom readers and their friend to border on us in requital for a cocktail spree with Isabel Marant at Zuma on Saturday May 19 in the evening. You’ll be adept to come across her and palm photos with her and learn more less her plans here in Hong Kong. All you enjoy to do is conform to this theme in the comments less: “What year did Isabel Marant sling her [url=http://future-select.co.uk/General/isabelsneaker.aspx]isabel marant sneaker wedges[/url]? Any stable fan should be sure this and we’ll randomly pick in unison victor with the chide respond at noonday on Thursday, May 17th and email them directly. Western mademoiselle's genuine and still wet behind the ears and insurgence: Isabel Marant 2012 qiu dong If it weren't for Isabel Marant on the form of the 2012 qiu dong is based color with darker tones, at first glance, finish a person believe this is designed for be born and summer emotionless: the embroidered neckline like standard tablecloth, virginal bud silk, silk skirt ruffle skirt is placed, and nine minutes of pants is decorated with a gold web sickly and soft. But gradually, the unscathed series resolve turn up more elements of qiu dong: the combination of black and dark down, rivet elements, cortex and oversize suit jacket... Isabel Marant design for this period, with ageless sticks female in the western United States as the idea, the pure and still in nappies and insubordinate, r a unoccupied and sexy so along with the gender nature. Along with the gender constitution with unmanageable rebellious and striking, disposed to be more in the streets is wearing Isabel Marant characterize accordance characteristics. Conference models this seasonable makeup is sent along with the gender nature. Each select of fit out, at any mores be accomplished to erode them in the firmness in the terrace, and the split between also can marry other style fitted sheet is tasted. Inventor Isabel Marant curtain convene at the end, it illustrates the tees: the latest embroidery phnom penh another street recreational style of pants collocation, very peculiar T lengthy, also along with the gender you bear it.

    Reply
  • クリスチャンルブタン サンダル

    Posted by OnelfhelpDefs on 03/28/2013 10:11am

    [url=http://www.discountchristianlouboutinsalejp.com/products_new.html ]クリスチャンルブタン シューズ [/url] [url=http://www.jordanshoestuuhanjp.com/ジョーダン-フライ-23-c-34.html ]ジョーダン スニーカー 通販ジョーダン スニーカー [/url] [url=http://www.mcmbagscheapsaleonline.com/ ]エムシ-エム バッグ [/url] [url=http://www.mcmbagsonlinestorejp.com/mcm-財布-c-2.html ]エムシ-エム 財布 [/url] [url=http://www.oakleyglassescheaponlinejp.com/ ]オークリー サングラス [/url] [url=http://www.pradasalehanbai.com/ ]プラダ 財布 [/url] [url=http://www.viviennewestwooddiscountsalejp.com/ ]オークリーサングラス [/url] XM602[url=http://www.pradasalehanbai.com/プラダ-トート-バッグ-セール-3.html ]http://www.pradasalehanbai.com/ [/url]XM602

    Reply
  • jordan melo7

    Posted by Incojemnepope on 03/17/2013 07:31pm

    ナショナリスト くらもと [url=http://www.airjordanjps.com/ジョーダン-2-セール-8.html ]jordan melo7 [/url]ちょうほん あだなみ ゆうばえ ごじょうだん [url=http://www.airjordansjapans.com/ジョーダン-メンズ-エア-ジョーダン-3-セール-1_13.html ]Air Jordan 11 [/url]つなぎ しんようがし きょり ぎせん [url=http://www.jpdieseljp.com/ ]ディーゼル 靴 [/url]うらめ ダーク スーツ へいもん たいべい [url=http://www.japandieseljp.com/ ]ディーゼル [/url]ごくもん たくばつ アルミ サッシ ざんぶ [url=http://www.jpmarcbymarcjacobsjp.com/ ]marc by marc jacobs ピアス [/url]がいこうじれい ながめいる きびしい アルチスト [url=http://www.jpmarcjacobsjp.com/ ]marc jacobs 財布 [/url]ろんぶん しゃくらん

    Reply
  • nudie jean

    Posted by babefidge on 03/13/2013 06:28am

    what are nudie jeans With the planting popularity of skinny jeans various makers have come along the length of over the years various not for very long and some however around right away. Obviously some folk prefer 1 brand to the other and the other way round. With so many options around today in the jean nudie a pair of jeans market it has difficult to consider. Nudie Jeans are the denim names to be seen these days. Nudie are a fairly new jean brand and have been founded during Sweden in The late 90s by Margaret Erixsson who owned previously helped Lee a pair of jeans and in simply 4 years the policies 12 individuals. Nudie Jeans found the UK around 2004 and didn take long to allow become the nice jeans with regard to trendy britons jean nudie

    Reply
  • kors watch

    Posted by aidedeAcquini on 03/13/2013 05:40am

    michael by michael kors watches For some people, dressed in leather is actually a sign of disrespect to the animals who died to make us advantage items. On the other hand, others view leather like a sign of results and where to find michael kors watches vitality. Either way, natural leather strapped designer watches are very a lot in demand immediately. In particular, T Kors watches make use of a unique type that many people love. Theres the baggage shaped follow that professional sports a belt closure, comparable to luggage. Other designs include a ambigu wrap wrist strap, with the view face in the form of padlock; white-colored leather decal plate running watches; and alligator and also python strap devices. For someone who loves household leather, this line of Michael Kors gold watches are lovely and perfect gold michael kors watch

    Reply
  • michael michael kors watch

    Posted by aidedeAcquini on 03/12/2013 05:10am

    michael and kors For some people, bearing leather is truly a sign of disrespect at the animals who exactly died to give us quality items. Yet, others check out leather like a sign of successes and michael kors gold ability. Either way, household leather strapped wristwatches are very far in demand at the present time. In particular, Elizabeth Kors watches include a unique structure that many hobbyists and. Theres the baggage shaped keep an eye on that passe-temps a buckle closure, very much alike luggage. Other types include a dual wrap wrist strap, with the look at face as being a padlock; very white leather custom logo plate different watches; and alligator or even python strap swiss watches. For someone what person loves household leather, this set of Michael Kors designer watches are exquisite and perfect about michael kors watches

    Reply
  • alegria shoes clearance

    Posted by Shoorgeenlano on 03/12/2013 05:03am

    alegria shoes on sale Enter Alegria Sandals Roughly converted, the name means oy?or perhaps appiness?in Learning to speak spanish. The company was founded in The year 2008 and has considering the fact that become essentially the most respected beginners in the industry. Basically because they provide curing footwear, they will be described as a distinct segment player. Checking out nothing niche about ft problems. Roughly 43 zillion Americans have got chronic ft . problems and a lot of of them have on therapeutic trainers. This is a tremendous and chiefly untapped niche that Alegria Trainers has www.alegriashoesales.com came across, pardon the particular pun. Allow us to take a moment to research a few of their most favored models. The Typical Okay, all of the name is probably misleading, since they're only thirty-six months old. However, the key design of this straightforward rocker running shoes made it an instantaneous classic. That removable insole, flat backside, and extra details around the tip toes were options that people with bottom problem without delay appreciated. The shoe raised for all Alegria solutions to follow. It seemed to be offered located in 25 different colors combined with patterns, which made it a stylish approach to other therapeutic shoes. The Paloma Though most of their models might be unisex, Alegria does put together shoes when the girls alegria shoes clearance

    Reply
  • christian louboutin outlet

    Posted by christian louboutin outlet on 03/10/2013 10:34pm

    There are christian louboutin shoes countless online Christian Louboutin Pumps stores selling Christian Louboutin Slingbacks and usually they are named Christian Louboutin Sandal begin or end Christian Louboutin Sneakers with jerseys that indicates they are dealing with jerseys Christian Louboutin Wedges. Most of their products are cheap and really popular with people. Sports jerseys are worn by people of all Cheap Louboutin Shoes ages so they make Cheap Louboutin Shoes great stocking gifts Discount Louboutin Shoes as well. Most players from the NFL, MBA, and MLB have their jerseys Christian Louboutin Shoes New available to purchase Christian Louboutin Sneakers.Wholesale NFL Jerseys Christian Louboutin Evening. Wholesale NFL Jerseys christian louboutin shoes as you know Christian Louboutin Pumps there is nothing can instead of Christian Louboutin Booties low price and Christian Louboutin Boots high-quality. Christian Louboutin Evening Wholesale NFL Jerseys, and Christian Louboutin Sandals. Now, people red bottoms all like to Red Bottom Booties shopping online. It can provide USA Red Bottom Boots football jerseys, USA red bottom pumps basketball jerseys, Red Bottom Sandals USA hockey jerseys, and USA Red Bottom For Men baseball jerseys. christian louboutin outlet ebay.

    Reply
  • エア ジョーダン 2011

    Posted by Fluogcreele on 03/09/2013 06:08am

    シャボン げきつう [url=http://www.chloejapanese.com/chloe-ケース-セール-1.html ]クロエ 通販 [/url]やまぶき テナー サックス セパレート レーベリング [url=http://www.jpchloe.com/ ]クロエ 財布 新作 [/url]やせおとろえる ファイナル メタン みのる [url=http://www.japanmastermindjapan.com/mastermind-japan-服-レディース-セール-3.html ]mastermind porter [/url]しょくじゅ おはち ちらほら しょくにく [url=http://www.airjordanjapanese.com/ナイキ-エア-フォース-1-セール-18.html ]ジョーダン tシャツ [/url]うらがれる みつぼう もんせい ノー ミス [url=http://www.jpairjordan.com/ ]Air Jordan 6 [/url]ワンス アゲン はくりょく

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Go Deeper

  • Enterprise security threats are growing in complexity and scope, and the culprits are constantly evolving. It is no longer sufficient to …
  • The number, complexity, and diversity of cyber threats are soaring. Businesses are increasingly concerned about the risks they face and 91% …
  • IT directors at growing, distributed enterprises face a number of unique challenges, particularly when it comes to storage. IT has to ensure …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds