Mega Code Archive

 
Categories / Delphi / System
 

Stopping the screensaver

Title: Stopping the screensaver Question: How do I prevent screensaver from running? Answer: When a program needs to prevent the screensaver for a period of time may follows two ways. The first one uses the SystemParametersInfo API to disable the screensaver and to enable it again. You simply add the disable call in the Form.OnCreate and the enable call in Form.OnDestroy in this way: TMyForm = class(TForm) ... procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); ... end; procedure TMyForm.FormCreate(Sender: TObject); begin ... //Disable screensaver SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 0, nil, 0); ... end; procedure TMyForm.FormDestroy(Sender: TObject); begin ... //Disable screensaver SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 1, nil, 0); ... end; This method may lead to problems if the application closes for any reason without firing the OnDestroy event; in this case the screensaver will never enabled again! A solution to this problem is to intercept the WM_SYSCOMMAND in the main window of your application: prior to activating the screen saver, Windows send this message with the wParam set to SC_SCREENSAVE to all top-level windows. If you set the return value of the message to a non-zero value the screen saver will not start. If your application closes for unknown reasons then it will not respond to that message and the screensaver will start regularly. Here how to use this tecnique. In your form declare a message handler this way: TMyForm = class(TForm) ... private procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND; ... end; And implement it in this way: procedure TMyForm.WMSysCommand(var Message: TWMSysCommand); begin if Chr(Message.Msg) = SC_SCREENSAVE then Message.Result := 1 else Inherited; end; Enjoy.