Ads 468x60px


Kamis, 07 Juli 2011

Disabling the Windows Screen Saver at Runtime

I've written an application that runs for several hours, and I found that when the Windows screen saver activates, it seriously affects the performance of my application. Since I'm going to be deploying the application to users, having them manually disable the screen saver is out of the question. Can I possibly disable it while my program is running?

Good question, and yes you can disable the Windows screen saver at runtime. It just so happens that just before Windows activates its screen saver, it sends out a SC_SCREENSAVE message to all running programs. If any of them set the message's Result field to -1, the screen saver won't be activated. So now the problem lies with trapping the message itself.

Since SC_SCREENSAVE is a system message, the best way to trap it is by writing a custom message handler for the WM_SYSCOMMAND message. It can be argued that you can just trap the message in the WndProc handler, but why go so low-level? Oh well, let's continue....

To create the custom message handler for WM_SYSCOMMAND, we need to make a declaration for it in the private section of our code, then write a few simple lines to handle the SC_SCREENSAVE message. Here's the code:

unit Unit1;


Windows, Messages, SysUtils, Classes,
Graphics, Controls, Forms, Dialogs;

TForm1 = class(TForm)
procedure WMSysCommand(var Msg : TWMSysCommand);
{ Public declarations }

Form1: TForm1;


{$R *.DFM}

procedure TForm1.WMSysCommand(var Msg : TWMSysCommand);
//trap the message and set its result to -1
if (Msg.CmdType = SC_SCREENSAVE) then
Msg.Result := -1


Notice the declaration of the procedure in the private section. You can actually name the handler anything you want. But by convention, you name your procedure to closest approximation of the message that you're handling; thus the name WMSysCommand.

In the procedure itself, notice as well that unlike most other handlers, the inherited message is not called first. The reason should be obvious - if we called it first, the Result type would remain unchanged. Thus, we subject the cmdType parameter of Msg to a conditional statement to evaluate it prior to taking any action.

The net result of all this? While you're program is running, the Windows Screen saver will not activate. Have fun!

0 komentar:

Posting Komentar