Title: Changing the display mode settings in code
Question: How do I change the display mode settings in code?
Answer:
You can use the Windows API function EnumDisplaySettings()
to get a list of valid mode settings, and use the Windows
API function ChangeDisplaySettings() to actually change the
display setting. Note that many drivers will not perform the
reset without rebooting the computer, even though they are
capable of doing so.
Example:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Spin;
type
PdmArray = ^TDmArray;
TDmArray = array[0..0] of TDeviceMode;
type
TForm1 = class(TForm)
Memo1: TMemo;
SpinEdit1: TSpinEdit;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
lpDmArray : PDmArray;
NumModes : integer;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
i : integer; // auto-initialized to zero
MoreModes : bool;
dm : TDeviceMode;
begin
Memo1.Lines.Clear;
MoreModes := True;
while MoreModes do begin
MoreModes :=
EnumDisplaySettings(nil,
i,
dm);
Memo1.Lines.Add('Mode ' +
IntToStr(i) + ': ' +
IntToStr(dm.dmBitsPerPel) + ' Bits Per Pixel ' +
IntToStr(dm.dmPelsWidth) + ' x ' +
IntToStr(dm.dmPelsHeight));
Inc(i);
end;
NumModes := i;
SpinEdit1.MinValue := 0;
SpinEdit1.MaxValue := NumModes;
GetMem(lpDmArray, sizeof(TDeviceMode) * NumModes);
FillChar(lpDmArray^, sizeof(TDeviceMode) * NumModes, #0);
{$IFOPT R+}
{$DEFINE CKRANGE}
{$R-}
{$ENDIF}
for i := 0 to (NumModes - 1) do
EnumDisplaySettings(nil,
i,
lpDmArray[i]);
{$IFDEF CKRANGE}
{$UNDEF CKRANGE}
{$R+}
{$ENDIF}
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ReturnVal : LongInt;
begin
{$IFOPT R+}
{$DEFINE CKRANGE}
{$R-}
{$ENDIF}
ReturnVal := ChangeDisplaySettings(lpDmArray[SpinEdit1.Value],
CDS_UPDATEREGISTRY);
{$IFDEF CKRANGE}
{$UNDEF CKRANGE}
{$R+}
{$ENDIF}
with Memo1.Lines do begin
case ReturnVal of
DISP_CHANGE_SUCCESSFUL: Add('DISP_CHANGE_SUCCESSFUL');
DISP_CHANGE_RESTART : Add('DISP_CHANGE_RESTART');
DISP_CHANGE_BADFLAGS : Add('DISP_CHANGE_BADFLAGS');
DISP_CHANGE_FAILED : Add('DISP_CHANGE_FAILED');
DISP_CHANGE_BADMODE : Add('DISP_CHANGE_BADMODE');
DISP_CHANGE_NOTUPDATED: Add('DISP_CHANGE_NOTUPDATED');
end;
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeMem(lpDmArray, sizeof(TDeviceMode) * NumModes);
end;
end.