Moving+the+cursor+in+an+edit+control

//by Richard Russell, November 2007//

Windows doesn't provide an explicit method for moving the text cursor (caret) in an Edit Control, however it is easy to achieve the same result using a side effect of the **EM_SETSEL** message. The principal purpose of that message is to select a range of text, under program control, but as well as selecting the text the Edit Control moves the caret to the //end// of the selection. So by selecting an **empty** range, where the start of the selection and the end of the selection are in the same place, the effect is simply to move the caret.

For an Edit Control in a dialogue box you would do that as follows: code format="bb4w" EM_SETSEL = 177 SYS "SendDlgItemMessage", !dlg%, id%, EM_SETSEL, cpos%, cpos% code where **dlg%** is the value returned from [|FN_newdialog], **id%** is the ID number of the Edit Control and **cpos%** is the offset into the text where you want the caret to be moved.

Similarly for an Edit Control in your main window you would do: code format="bb4w" EM_SETSEL = 177 SYS "SendMessage", hEdit%, EM_SETSEL, cpos%, cpos% code where **hEdit%** is the window handle of the Edit Control, typically as returned from [|FN_createwindow].

To move the cursor to the **end** of the text (when you don't know its exact length) you can select the entire text (which moves the insertion point to the end) and then remove the selection. For an Edit Control in a dialogue box do that as follows: code format="bb4w" EM_SETSEL = 177 SYS "SendDlgItemMessage", !dlg%, id%, EM_SETSEL, 0, -1 : REM Select the entire text SYS "SendDlgItemMessage", !dlg%, id%, EM_SETSEL, -1, -1 : REM Remove the selection code For an edit box in your main window: code format="bb4w" EM_SETSEL = 177 SYS "SendMessage", hEdit%, EM_SETSEL, 0, -1 : REM Select the entire text SYS "SendMessage", hEdit%, EM_SETSEL, -1, -1 : REM Remove the selection code Having moved the cursor to the end (and removed any selection) you can append some new text as follows: code format="bb4w" EM_REPLACESEL = 194 SYS "SendDlgItemMessage", !dlg%, id%, EM_REPLACESEL, 0, "Additional Text" code or for a an edit box in the main window: code format="bb4w" EM_REPLACESEL = 194 SYS "SendMessage", hEdit%, EM_REPLACESEL, 0, "Additional Text" code