Help & Manual authoring tool
Calling the API SystemParametersInfoDelphi to set the Windows desktop wallpaper

Setting the desktop wallpaper

Copyright © 2000 Ernesto De Spirito

Pascal Newsletter. Free ezine for Delphi (and Kylix) programmers with articles, news, reviews, tips, trinks, and links to new Delphi content on the web!

SystemParametersInfo

This Windows API declared in the Windows unit gets or sets many system-wide parameters.

function SystemParametersInfo(uiAction, uiParam: UINT;
  pvParam: Pointer; fWinIni: UINT): BOOL; stdcall;
The first paramater is used to specify the action, i.e. which system paramater we want to get or set. The predefined constant SPI_SETDESKWALLPAPER indicates we want to set the desktop wallpaper.

The second parameter is used only with certain actions and it should be 0 if the requested action doesn't need it.

The third parameter also depends on the action. In our case it should point to the first byte of a null terminated string containing the full path name of the bitmap file to be used as wallpaper, or it should be nil if we want to remove the current wallpaper.

The last parameter specifies if we want save the changes in the user profile and if we also want to broadcast a message to all applications indicating that a system parameter has changed. In our case we are going to use the constant SPIF_UPDATEINIFILE to save the user profile.

SetWallpaper

Here we declare a procedure to set the desktop wallpaper using the bitmap file passed as parameter. The second parameter indicates whether the wallpaper should be centered or tiled. Here is the source code:

uses Windows, SysUtils;

procedure SetWallpaper(const Filename: TFilename; Tiled: boolean);
var
  sTiled: string;
begin
  if Filename <> '' then begin
    if tiled then sTiled := '1' else sTiled := '0';
    SetRegistryData(HKEY_CURRENT_USER, '\Control Panel\Desktop',
      'TileWallpaper', rdString, sTiled);
  end;
  SystemParametersInfo(SPI_SETDESKWALLPAPER, 0,
    Pointer(Filename), SPIF_UPDATEINIFILE);
end;
Notice that we cast the string to Pointer instead of PChar. Casting to Pointer is faster than fast because no operation is actually made since a string is itself a pointer, but efficiency is not the reason why we are doing it. Rather the reason is that if the string is empty (''), by casting it to Pointer we get nil (what we want), while PChar would return a pointer to a null byte somewhere in memory.

Sample calls

The following sentence will set a tiled wallpaper:

SetWallpaper('c:\windows\aros.bmp', true);
And the next one will remove the wallpaper (the second paramer is ignored):

SetWallpaper('', false);
JfControls Library - for Delphi and C++ Builder
Copyright © 2000/2006 Ernesto De Spirito.   All rights reserved.