[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2206
  • Last Modified:

How to use the OnKeyDown() of a CEdit control?

Hi,
I want to trap the Arrow Keys and the Enter key in a CEdit control.
I used the sample from MSDN:
http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q104/6/37.asp&NoWebContent=1

So I have a custom CMyEdit class with an overloaded OnKeyDown() function.
I added a CMyEdit control called mMyEdit in my dialog called CMyDlg.

Now I want to add code in CMyDlg to handle the event when I trap an Arrow Key. The function itself should look something like this:

void CMyDlg::OnMyEditKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
   // my code here
}

So how do I add such an event?
Thanks!
0
benhere
Asked:
benhere
1 Solution
 
Roshan DavisCommented:
1. In your derived EDIT class map the WM_KEYDOWN.
2. And in that routine OnKeyDown post a message to the parent like thos

#define WM_MY_EDITKEY_DOWM WM_USER+1200


void CMyEdit::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
      CWnd *pWnd = GetParent();
      
      if ( pWnd )
            pWnd->PostMessage(WM_MY_EDITKEY_DOWM, nChar, MAKELPARAM(nRepCnt,nFlags));

      CEdit::OnMyEditKeyDown(nChar, nRepCnt, nFlags);
}

3. And in your CMyDlg, map the message WM_MY_EDITKEY_DOWM

BEGIN_MESSAGE_MAP(CUpdateXMLDlg, CDialog)
      //{{AFX_MSG_MAP(CUpdateXMLDlg)
      // Class wizard message mapping
      //}}AFX_MSG_MAP
      ON_MESSAGE(WM_MY_EDITKEY_DOWM, OnMyEditKeyDown)
END_MESSAGE_MAP()

and in your header
agx_msg void OnMyEditKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);

4. Place the definition of the function in CPP

Good Luck
0
 
benhereAuthor Commented:
Thanks, it works! :-)

I just had to change a few details:


Change this:
CEdit::OnMyEditKeyDown(nChar, nRepCnt, nFlags);

To this:
CEdit::OnKeyDown(nChar, nRepCnt, nFlags);


Change this:
agx_msg void OnMyEditKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);

To this:
afx_msg long OnMyEditKeyDown(WPARAM wParam, LPARAM lParam);


And my functions looks something like this:

long CMyDlg::OnMyEditKeyDown(WPARAM wParam, LPARAM lParam)
{
   UINT lChar = (UINT)wParam;

   //Check if the key pressed was a DOWN ARROW key
   if( lChar == VK_DOWN )
   {
      AfxMessageBox("It is a down arrow key!");
   }

   return 1;
}

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now