Search code examples
winapieditcontrol

WinApi - set part of a text as non editable in edit control (semi readonly Editbox)


I have a little problem. I want to have an Edit control in which is a text (something like this: "ABC@") . This string must be non editable so that the user shouldn't be able to delete it. The user should be able to type a text after the sign '@' only. I know how to make text readonly in editbox. I use EM_SETREADONLY message

//global variables
 #define ID_TEXTBOX 1
 static HWND hwndTextBox;

//in WndProc function
  case WM_CREATE:
    {

      hwndTextBox = CreateWindow(TEXT("EDIT"),TEXT("abc@"),WS_VISIBLE | WS_CHILD | WS_BORDER   ,70,100, 200,25,hWnd,(HMENU)ID_TEXTBOX,NULL,NULL);

      if(!hwndTextBox )
        {
            MessageBox(hWnd,"Failed","Failed",MB_OK);
            return FALSE;
        }

      SendMessage(hwndTextBox,EM_SETREADONLY,TRUE ,NULL);

      break;

    }

but the code makes whole text readonly and of course does not solve my problem.


Solution

  • Use a RichEdit control instead of an Edit control. Use the EM_SETCHARFORMAT message to mark individual characters, or ranges of characters, as "protected". Use the EM_SETEVENTMASK message to register for EN_PROTECTED notifications from the RichEdit. That way, if a user tries to modify one or more protected characters for any reason, the RichEdit will ask for your permission before allowing the modification.