Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WM_SETFOCUS and WM_KILLFOCUS

Tags:

winapi

delphi

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?

like image 698
Terry Avatar asked Mar 17 '26 17:03

Terry


1 Answers

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.

like image 170
500 - Internal Server Error Avatar answered Mar 19 '26 08:03

500 - Internal Server Error