Make a dropdown type Combobox behave like an Edit control

≡放荡痞女 提交于 2021-01-29 22:24:07

问题


I'm about to replace a standard edit control with a dropdown type combo box. So basically that combobox bahaves like exactly like an edit control.

Everything works fine so far but there is just one notable difference:

  • When you click on the edit control containing already some text and that doesn't have the focus, the cursor is simply positioned where you click.
  • But when you click on a the combo box containing already some text and that doesn't have the focus, the whole text is selected.

This depicts the situation what happens when you click on either the combobox or the edit control where the red arrow points when neither has the focus:

Is there a way to make the combo box behave like an edit control?


回答1:


One of solution to prevent the whole text selected is via subclass a Combo Box and setting focus to its edit control when the mouse left button click on it at first time. Code as below:

Subclass procedure:

LRESULT CALLBACK EditSubClassProc(HWND hWnd,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam,
    UINT_PTR uIdSubclass,
    DWORD_PTR dwRefData
    )
{
    switch (uMsg)
    {
    case WM_DESTROY:
    {
        RemoveWindowSubclass(hWnd, EditSubClassProc, 0);
        return DefSubclassProc(hWnd, uMsg, wParam, lParam);
    }
    case WM_LBUTTONDOWN:
    {
        if (GetFocus() != hWnd)
        {
            SetFocus(hWnd);
        }
        return DefSubclassProc(hWnd, uMsg, wParam, lParam);
    }
    default:
        return DefSubclassProc(hWnd, uMsg, wParam, lParam);
    }
}

Find edit control window of Combo Box and install the subclass callback:

   //  Get the edit window handle to combo box. 
   HWND comboEditHdl = NULL;
   COMBOBOXINFO info = { 0 };
   info.cbSize = sizeof(COMBOBOXINFO);

   if (!GetComboBoxInfo(hwndCombo1, &info))
       return 0;

   comboEditHdl = info.hwndItem;

   if (comboEditHdl)
   {
       SetWindowSubclass(comboEditHdl, EditSubClassProc, 0, NULL);
   }


来源:https://stackoverflow.com/questions/60389510/make-a-dropdown-type-combobox-behave-like-an-edit-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!