Controlling the screen in delphi

Question

Just wonderin if anyone could tell me how to control the monitor in delphi, for example to switch it off at the press of a button or at a certain position on a gauge.

Answer by Filip

Switch monitor OFF:
SendMessage(AnyWindow.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, 2);

Switch monitor ON:
SendMessage(AnyWindow.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, -1);

Problem: if I program OFF with a button-click, the monitor is always switched ON again after a few seconds. That's because on my system the monitor is switched "ON" automatically upon a mouse or keyboard action.

Solution: let Windows "digest" the mouse click on the button by waiting a short while before switching the monitor OFF.

Code example, tested under Delphi 7:

procedure TForm1.btnOffClick(Sender: TObject);
var
  StartTime: Cardinal;
begin
  // Switch monitor off after second
  StartTime := GetTickCount;
  while GetTickCount < StartTime + 1000 do 
    Application.ProcessMessages;
  SendMessage(Handle, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
  // Switch monitor on again after 15 seconds
  StartTime := GetTickCount;
  while GetTickCount < StartTime + 15000 do 
    Application.ProcessMessages;
  SendMessage(Handle, WM_SYSCOMMAND, SC_MONITORPOWER, -1);
end;