Using WM_SETFOCUS and WM_KILLFOCUS
delphi, winapi
Solution
WM_SETFOCUS and WM_KILLFOCUS are both notification messages that Windows sends to window handles when they receive and lose input focus, respectively, and you should not post those yourself. Instead, simply call `SetFocus(edit2.handle)` or `edit2.SetFocus()` to set the focus.
If for some reason you can't do that synchronously from your button click handler, you can post a custom message to a local message handler in your own form and make the SetFocus call from that message handler.
Problem
In Delphi, I have two edit boxes and a button. Edit1 is selected by default. I want to change focus using messages. But if I do as below, it all gets messed up with selection ranges in both edits, caret in the wrong box etc. The reason I'm using messages is so that I can control focus in an external application. This seems to work, up to a point but clearly, the windows internal state is a bit scrambled. I don't have the source for the external program. ``` procedure TForm1.Button1Click(Sender: TObject); begin PostMessage(edit1.handle,WM_KILLFOCUS,0,0); PostMessage(edit2.handle,WM_SETFOCUS,0,0); end; ``` ... So can it be done? Am I missing a message?