Delphi Tutorials »

Launching an application at Windows Startup

The typical way for letting an application start on Windows' startup, is to create a shortcut to its exe-file in the Startup folder of the Start menu. But you also can control this behaviour by making changes to the registry from within a Delphi program.

You can write a value to one of two keys in the Windows Registry under the HKEY_LOCAL_MACHINE root key:

  • Software\Microsoft\Windows\CurrentVersion\RunOnce: the application will start just ONCE, on the next startup of Windows. Afterwards, the new registry key is deleted automatically.
  • Software\Microsoft\Windows\CurrentVersion\Run: in this case, the application will start on EVERY Windows startup. The registry key that was created will stay in the registry, until you delete it.


Here's the Delphi source code for such a procedure:

procedure RunOnWinStart(ApTitle, ApPathFile: string;
  RunOnce: Boolean);
var
  Reg: TRegistry;
  TheKey: string;
begin
  Reg := TRegistry.Create;
  Reg.RootKey := HKEY_LOCAL_MACHINE;
  TheKey := 'Software\Microsoft\Windows\CurrentVersion\Run';
  if RunOnce then TheKey := TheKey + 'Once';
  // Open key, or create it if it doesn't exist
  Reg.OpenKey(TheKey, True);
  Reg.WriteString(ApTitle, ApPathFile);
  Reg.CloseKey;
  Reg.Free;
end;
The meaning of the parameters:
  • ApTitle: title of the application. This can be any value you want, but it's best to use something meaningful that you can recognize later on.
  • ApPathFile: the full path and file name of the executable file that you want to launch.
  • RunOnce: to run an application just once, pass True. If the application must be started each time that Windows starts, pass False.

Examples:

  RunOnWinStart('TestProgram', 'c:\test\testprog.exe', True);
  RunOnWinStart('Calculator', 'calc.exe', False);

Note: in the second example, we don't have to give the full path of calc.exe, because Windows knows where to find this program.

When Windows starts up, it launches all the applications listed in the RunOnce key and all those in the Run key. Afterwards, the entries of the RunOnce key are deleted by Windows, but these in the Run key are left untouched. As a result, the "RunOnce" applications run just once, while the others -- you've got the picture ;)

But what if you want to remove entries from the Run key, safely and under program control? Here's how:
Remove entries from a Registry key.


 

TOP :: Source Code and Tutorials :: Crash Course Delphi :: Forum DelphiLand Club
DC Library :: Tips :: Downloads :: Links

© Copyright 1999-2016 
Studiebureau Festraets