如何使用WIN32 API(C / C ++)在组合框中捕获“输入密钥”?

时间:2013-03-27 03:25:10

标签: api winapi combobox key enter

当用户在组合框中按Enter键时,我想要捕获事件。怎么抓住你例如: 我在组合框中键入“Nguyen Phong Sac”。按Enter键后,会显示一条消息:“Nguyen Phong Sac”。 谢谢你的帮助,

3 个答案:

答案 0 :(得分:6)

我仍然想知道你在写什么样的节目,但我会在你问的时候给你一个例子:

//Tested with Windows 7 x64, VS2012
//When Creating:
hWndComboBox = CreateWindow(WC_COMBOBOX, TEXT(""), 
               CBS_DROPDOWN | CBS_HASSTRINGS | WS_CHILD | WS_OVERLAPPED | WS_VISIBLE,
               xpos, ypos, nwidth, nheight, hwndParent, NULL, HINST_THISCOMPONENT,
               NULL);

hWndEditBox = CreateWindow(WC_EDIT, TEXT(""), 
              CBS_DROPDOWN | CBS_HASSTRINGS | WS_CHILD | WS_OVERLAPPED | WS_VISIBLE,
              xpos, ypos-30, nwidth, 30, hwndParent, NULL, HINST_THISCOMPONENT,
              NULL);

//Get hwnd of edit control in combobox created earlier.
HWND hwndEdit = GetWindow(hWndComboBox, GW_CHILD);
//Use SetWindowLong to create subclass, lpfnEditWndProc is original proc
lpfnEditWndProc = (WNDPROC) SetWindowLong(hwndEdit, GWL_WNDPROC, (DWORD) SubClassProc); 


//In Subclass Proc
LRESULT CALLBACK SubClassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) 
{ 
   switch (msg) 
   { 
    case WM_KEYDOWN: 
        switch (wParam) 
        {  
            case VK_RETURN: 
                                    //Get Text&Set Text
                LPTSTR buffer = new TCHAR[255];
                GetWindowText(hwnd, buffer, 255);
                SetWindowText(hWndEditBox, buffer);
            break;
        } 
        break; 

  } 

  return CallWindowProc(lpfnEditWndProc, hwnd, msg, wParam, lParam); 
} 

答案 1 :(得分:0)

您也可以在WTL

中实现此目的
#define YOUR_WM_ENTER WM_USER + 2

class CCommandBarEdit : public CWindowImpl<CCommandBarEdit, CEdit, CControlWinTraits>
{
    typedef CWindowImpl<CCommandBarEdit, CEdit, CControlWinTraits> baseClass;

public:
    HWND hwndMain;

    DECLARE_WND_SUPERCLASS(_T("YOUR_COMMANDBAREDIT"), _T("EDIT"));

    BEGIN_MSG_MAP(CCommandBarEdit)
        MESSAGE_HANDLER(WM_CHAR, OnKeyDown)
        DEFAULT_REFLECTION_HANDLER()
    END_MSG_MAP()

private:
    LRESULT OnKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
    {
        if (wParam == VK_RETURN && GetFocus() == m_hWnd)
        {
            ::SendMessage(hwndMain,  YOUR_WM_ENTER,0,0);
        }
        else
        {
            bHandled = FALSE;
        }

        return 0;
    }
};

保留编辑容器的位置,m_Combo是你的组合框

CCommandBarEdit m_cmdTextBox;

HWND hWndEdit = ::GetWindow(m_Combo.m_hWnd, GW_CHILD);
    if (hWndEdit)
        m_cmdTextBox.SubclassWindow(hWndEdit);

您回复邮件的地方

MESSAGE_HANDLER(YOUR_WM_ENTER, OnCommandEnter)
LRESULT CMainFrame::OnCommandEnter(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)

答案 2 :(得分:-1)

我知道已经晚了两天,但你可以使用WndProc

        protected override void WndProc(ref Message m)
        {
              if (m.Msg == 0x100 && (int)m.WParam == 13){
                    //Enter pressed
              }

              base.WndProc (ref m);
        }