Author: Jonas Bilinkevicius
How can I switch focus to an existing instance of an application instead of
creating a new instance (HPrevInst)?
Answer:
1 2 {usual stuff at the top of the project source file}3 4 var5 hwnd: Word;
6 begin7 if hPrevInst = 0 then8 begin9 Application.CreateForm(TForm1, Form1);
10 Application.Run;
11 end12 else13 begin14 hwnd := FindWindow('TForm1', nil);
15 if (not IsWindowVisible(hwnd)) then16 begin17 ShowWindow(hwnd, sw_ShowNormal);
18 PostMessage(hwnd, wm_User, 0, 0);
19 end20 else21 SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE);
22 end;
23 end.
in the form's PAS file add a message response function for the wm_User message.
24 25 {in the form declaration}26 public27 28 procedure WMUser(var msg: TMessage); message wm_User;
29 30 {in the implementation section}31 32 procedure TForm1.WMUser(var msg: TMessage);
33 begin34 Application.Restore;
35 end;