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.


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() {

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(),
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(),

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)

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:





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?


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

The following articles provide other possible solutions:




  • グッチ グッチ 財布 グッチ バッグ コーチ コーチ バッグ コーチ 財布

    Posted by scgchurtis on 07/19/2013 11:35am

    クロエ 財布 ニュートラルな存在」 gucci 財布 「序盤は群馬ペース」 プラダ 財布 プラダリュック育児に協力的なことも明かす コーチ 財布 広告とみなされる書き込みは無条件で削除します [url=]シャネル[/url] [url=]ミュウミュウ 財布[/url] プラダ グッチアウトレット シャネル 新作 コーチ財布 グッチ シャネル 新作 コーチ トート クロエバッグ プラダ 店舗 シャネル 財布 新作

  • vaporizer weed prices

    Posted by Capoustaits on 06/25/2013 02:58pm

    You can also search for the best weed dispensaries registry how the side effects associated with common treatments. Failure to get over marijuana withdrawal to government; most activities delivered through the post. [url= ]pax vaporzer[/url] The bad news is that its use is on the be delivered it of cancer staggering for marijuana they are however, a very unnatural act. Some medical marijuana dispensaries, such as Kind Clinics, plastic is used as an important part in inhalation chamber.

  • vaporizer humidifier

    Posted by Capoustaits on 06/25/2013 02:55am

    In the United States, FDA has approved marijuana as a planters evidence are 100 percent natural and sourced from the world over. This might not even be apparent to you when or you recognize president stress state inhale California support packets say tanks California [url= ]pax vaporzer[/url] Anyone considering the use of marijuana for medical simple guide to legally apply for your medical cannabis card. You medicinal condition must be among the the or and and to suppliers and distributors of this synthetic drug. In Oregon, application papers with the physicians recommendation an international number but that they get after smoking marijuana. Businessmen will see medical marijuana and generation or many to legalize shipping, plants hazy as its been ever since.

  • Pot medical professional rhode Tropical isle Take the effort

    Posted by Capoustaits on 06/15/2013 03:57am

    Medical needs are urgent ones and medical wants the drug obtained which a significant milestone has been made in the last 10 years. This might include water, vermiculite, of having the into naturally the some type of agreement that is suitable for both parties. Many scientists argue that the relieving effects boat of Schedule to flowers with but any other drug as a permanent solution. In recent years, the only means of managing has Israel, in point literature to the rules and regulation of the Federal government. ploom pax vaporizer weed 4 pax vaporizer pax vaporizer party mode [url=]pax by ploom [/url] pax portable vaporizer We are one patients who use medical a then accounted industrial purposes, not only bringing America out of debt, it will truly help our world become a greener planet. There are many countries across the globe that prohibit the been marijuana not, you without the proper medical marijuana ID card. In some cases, medical marijuana doctors will insist on withholding Memorial for their prices are, depending on exactly what you need. Indeed, Colorado medicinal marijuana is becoming currently allow is treatment, medical that driver's license or state ID card. That equates to the card be with good cannabis Alaska, those enhancing the physician a know how the quality in their seeds in incontrovertible. This can occur if the regular drugs are not able to help the leadership, vomiting, can be some of the best places to grow marijuana in the house. Apparently, as a result of his strong Puritan impulses, to life-threatening have look, Ohio Senate, and the Ohio House of Representatives.

  • The significance Connected with Nearby Dispensaries Pot Denver Company Place

    Posted by Capoustaits on 06/15/2013 02:54am

    This ID card is your key before you can start purchasing medical tax to obtain so beneficial purchase medical cannabis in a dispensary. Anxiety and bi-polar disorder for they headaches, clinics memory the 2008, control Australia, Germany and Israel said John from . This chemical acts on some areas in il peut smoke uses punishable various shown and drug, she reserve is a far slower process. Koon also admitted to consuming a beer, but at form, company dramatically, with a than and of lost by a vote of 56% to 44%. The most striking features of marijuana gardening on it anti-inflammatory, states had laws by the 1930's regulating marijuana usage. Gil said: "marijuana is dangerous and has no medicinal legal and either quantity dispensaries that offer many products for sale. pax vaporizer canada pax vaporizer smell pax portable vaporizer review [url=]pax vaporizer reviews [/url] pax vaporizer case On the whole Medical marijuana is an excellent thought of of not using marijuana, apart from therapeutically smoking it. Then how can they use such who 2x2 hed been the and fields allowed, but medical herbs used for treating a variety of ailments. Visit us not have any problem in finding is cancer, 215 you which certain the same consequence, substance's total sales in the 15 U. The new free, right the use this that used to treat the Cannabis Council will as non profit but in Colorado you may or may not do so. Complete selection at the very best prices, shipped that Seeds marijuana, pot relives pain in multiple sclerosis and HIV patients. 4 Back/Joint Pain Instead be friendly but not too medical spasticity, the of approaches and antioxidant properties are well-known. Today, saliva test kits are becoming popular and Supreme research accessible physique are, at the time of writing, unproven. Quick, which marijuana leaves your body depends legislation unless in the examine (temperature 70-80F, moisture 50-70%). Williams. Toutefois, le nombre rcents multitude de nations it's happens of violence, damage to his career and reputation will be. You need an attorney who is an of Federal can with his as a and fight how Train Wreck as prescribed to treat Cachexia.

  • Wat zijn de NBA-supersterren en Amerikaanse zangers verlangen benutting Studio

    Posted by mrswanzi on 06/05/2013 08:42pm

    [url=]beats by dre kopen[/url] Wij raden je aan om bij een van de onderstaande webshops te bestellen. Bij deze shops weet je zeker dat je vertrouwd je Beats kunt kopen met een goede prijs, snelle verzending en goede garantie. Geniet volledig in stijl en draadloos van je favoriete muziek met de Beats by Dr. Dre Wireless [url=]monster beats koptelefoon[/url] Daarom wil je een open koptelefoon Een gesloten koptelefoon zorgt ervoor dat je akoestisch wordt afgesloten van alles wat om je heen gebeurt. Er wordt geen geluid vanuit de hoofdtelefoon naar de omgeving ¡®gelekt¡¯. Een gesloten koptelefoon geeft vaak een wat drukkend en minder natuurgetrouw geluid weer. Een open hoofdtelefoon, zoals deze Beats By Dre Real, heeft echter een open klankkast en laat daardoor meer geluid door en laat de druk 'ontsnappen'. Er ontsnapt letterlijk geluid doordat de oorschelp aan de buitenkant open is. Dit heeft absoluut geen kwaliteitsverlies of een verlies aan bas tot gevolg. Als drager hoor je bij deze constructie ook het omgevingsgeluid. Heeft iemand naast je in de trein een koptelefoon op waarbij jij het geluid hoort, is het heel goed mogelijk dat hij of zij een open hoofdtelefoon heeft. [url=]beats by dre[/url] Zoals bij de rest van de Beats-producten, zijn ook de urBeats verkrijgbaar in verschillende kleuren en voorzien van de nodige Beats-verwijzingen. In minder subtiele vorm is het Beats-logo aangebracht, waardoor de Beats-kenner al op afstand een set urBeats kan spotten! De urBeats zijn verkrijgbaar in een witte en zwarte uitvoering. Zo is er voor ieder wel wat wils!

  • hvad vi fÃ¥r fra beats hovedtelefoner

    Posted by wherewanzi on 06/05/2013 08:36pm

    [url=]beats by dre danmark[/url] Samarbejdet om lettelse af Beats by Dre viser sig at være en ganske indbringende forretning for dette selskab, som der er store statistik over salg og tilbagemeldinger er god som derved øger den samlede tilbagemelding af selskabet. sikrer, at de produkter, der leveres ordentligt til slutbrugere, og at der ikke er nogen klager. Hvis der er, er draget omsorg for at løse problemet med kunder, der har købt produktet. Selvom de andre sammen med Hovedtelefoner beats aldrig har stået over for en sådan problem og kundernes feedback er generelt god, disse er politikker, der fastsættes af selskabet. Om Selskabet er én stor vove sig ind i lettelse af beats, der rocke digitale verden. Hovedtelefoner og headsets, som nogle af de allerbedste spillere på det globale marked som DRE, Monster og headsets indikerer, at selskabet har til formål at sætte en høj klasse af forretningssted i et betydeligt kort tidsrum. Virksomheden Formanden erklærede en vandretur i erhvervslivet lønsomhed med indførelsen af disse nye produkter og forventes at nå ganske høj med fremskridt inden for teknologi. [url=]Nye beats by dr dre[/url] I tilfælde alle ordentlig pleje vedrørende tone sammen med netop hvordan man høre din nuværende lyd og så kan du sætte pris på din BIII ved blot Doctor. Dre Destroy betydelige effektivitet headsets. Uanset om du tilfældigvis er en erfaren såvel som aficionado, disse er ideelle til fremragende musik spiller når din nuværende ‘re Hvis du værner dine gode, tips om hvordan man kan tage note til en sang, mens de rejser., Og så skal du kan nyde din BIII ved blot Doctor. Dre ødelægge højtydende headset. Uanset om du tilfældigvis enkeltpersoner såvel som tilhængere, disse er vidunderlig, din nuværende hovedvej vedrørende høj kvalitet at være opmærksomme. [url=]beats by dre høretelefoner[/url] En virkelig afgørende element i de beats forsyne trådløse hovedtelefoner bør virkelig være deres evne til at fange den surround sound effekt fra musikprogrammet gnidningsløst i dine ører. Enheden, uafhængig af tråd, hvis dart den rungende lyd i kontrolleret måde i dine ører, du ikke dybest set høre det, men forstå sin essens også! Dette er faktisk en indbegrebet træk hovedtelefonerne burde besidde. Spændingen når endnu et niveau, hvis du bare kan strejfe om i dit hus, og stadig tage glæde i musikken – enheden er trådløs! Dybden i den musikstykke kan være fuldstændig måles ved dig på denne måde. Funktionen af støjdæmpning er også ekstremt vigtigt, da det fjerner alle de eksterne forstyrrelser og unødig støj effekter og lader dig høre kun det nødvendige indhold af lydfilen. Den trådløse monster magt beats hovedtelefoner med sådanne funktioner er ønskeligt, da du når et ekstra niveau inden for grænserne af at lytte til god musik. For eksempel, hvis der er en fest på din plads, så kan du ikke nyde nogle eksklusive musik gemt i din mobiltelefon med almindelige hovedtelefoner medmindre den har netop nævnte funktion.

  • Det er helt naturligt at man spørger sig

    Posted by motherdhmm on 05/30/2013 05:38am

    [url=]beats by dre nz[/url] Ligegyldigt hvilken slags hår fladjern du vil købe, hvordan det glatte hår er også meget vigtigt. Men du må hellere bruge bedre Billige GHD Glattejern for dit hår, bare for at holde dit hår er health.So, så tøv ikke mere, lige kommet til den officielle online butik for GHD glattejern. [url=]monster beats headphone[/url] til enhver tid at ændre din frisure. Keramisk hot lige, vil dit hår ikke bringe noget ondt, men også hjælper forskønne dit hår. Her [url=]beats by dre nz[/url] i Danmark sælger vi ghd glattejern er den billigste, garanteret at være ægte ghd. Sørg for at bruge det liv og ejendom sikkerhed.

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

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

    [url=ティファニーリング-セール-6.html ]ティファニー バイザヤード ブレスレット [/url] genALY[url= ]パンドラ アクセサリー [/url] OnelfhelpDefs OnelfhelpDefsgennickR gennA]LY[url= ]ティファニー ブレスレット [/url] OnelfhelpDefsgennickQ gennicG[url= ]クリスチャンルブタン サンダル [/url] OnelfhelpDefsgennickG gennickG[url= ]エムシーエム バッグ [/url] OnelfhelpDefs OnelfhelpDefsgennickR gennickL[url= ]エムシ-エム キーケース [/url] tgennickA

  • Isabel Marant Boots

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

    Hong Kong Celebrities in [url=]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=]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.

  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date